lee / simple-container
反射特定类的 PHP 库
1.0.1
2019-02-26 07:13 UTC
Requires
- php: >=7.1.0
Requires (Dev)
- php-coveralls/php-coveralls: ^2.1
- phpunit/phpunit: ^7.0
This package is auto-updated.
Last update: 2024-08-26 19:15:12 UTC
README
简介
这是关于简单容器,帮助开发者了解反射的工作原理。
用法
首先,您必须指定一个要注入的类。
例如,我们假设您想要注入以下 Profile
类
class Profile { protected $userName; public function __construct($userName = 'lee') { $this->userName = $userName; } public function getUserName() { return $this->userName; } }
然后我们使用 Container
类来注入这个 Profile
类。
use Lee\Container\Container; $container = new Container(); $container->set(Profile::class); $profile = $container->get(Profile::class); echo $profile->getUserName(); // lee
如果您想注入的类其构造函数参数没有默认值,我们应该自己指定它们。
以下是一些示例代码
class Profile { protected $userName; public function __construct($userName) { $this->userName = $userName; } public function getUserName() { return $this->userName; } }
然后我们使用 Container
类来注入这个类。
use Lee\Container\Container; $container = new Container(); $container->set(Profile::class); $profile = $container->get(Profile::class, ['userName' => 'Peter']); echo $profile->getUserName(); // Peter
参考
这个 simple-container 实现了这篇 文章。
然而,我们参考的文章在一些方法上是错误的。
我们决定实现这个 PHP 包,以完成正确的容器示例。