由于 PHP 是一种解释型语言,因此您拥有一个动态类型系统。这意味着,例如单个变量可以保存多种类型的值:
$foo = "Now I'm a string";
$foo = 42; // And now I'm a number
现在问题变成了“类型化对象”的位置。在PHP Version 5 type declarations 中引入了,因为动态类型系统带来了一些问题。首先,您失去了拥有static type checking 的能力。
例如,以下函数可能会出现异常:
function doSomething($a, $b)
{
// imagine costly and long running operation here...
return $a + $b;
}
echo doSomething(1, 2); // -> 3
echo doSomething('hello ', 'world'); // -> Would result in an error, but only at runtime
为了抵消 PHP 解释器可以用来推断函数参数(和返回类型等)的类型提示。
此外,现在我们已经有了类型,我们可以使用一种称为 reflection 的技术来内省函数或方法期望传递到的内容以提供正确的对象。
所以转一圈回答你的问题:
类型化的对象仅仅意味着类型提示方法参数,因此 laravel 的服务容器可以推断您希望将什么对象注入到您的方法中。
// not using typed objects:
class Firewall
{
protected $logger;
protected $filters;
public function __construct($logger, ...$filters)
{
$this->logger = $logger;
$this->filters = $filters;
}
}
// using typed objects:
class Firewall
{
protected $logger;
protected $filters;
public function __construct(Logger $logger, Filter ...$filters)
{
$this->logger = $logger;
$this->filters = $filters;
}
}
其他信息:
你想注入你的依赖而不是在你的类中创建它们的原因是为了获得inversion of control,最好是通过注入接口,这样你就可以在顶部获得loose coupling。