<?php class Di { protected $providers = []; //注册服务 public function register($id,$val) { $this->providers[$id] = function () use ($val){ return new $val(); }; } //get方法 public function __get($id) { return $this->providers[$id](); } } class User{ public function test() { echo 'user:test'; } } class Student{ public function test() { echo 'student:test'; } } $di = new Di(); $di->register('user',User::class); $di->register('student',Student::class); $di->user->test()."/r/n"; $di->student->test();