考虑这个简单的类:
<?php declare(strict_types=1);
class Blog
{
private $user;
public function __construct(string $user)
{
$this->user = $user;
}
public function post ()
{
return 'New post by '.$this->user;
}
}
使用基本的依赖注入可以正常工作:
$blog = new Blog('Bob');
echo $blog->post();
// no errors, works as expected
$blog = new Blog(7);
echo $blog->post();
// fatal errors with TypeError, works as expected
但是当使用诸如league\container之类的依赖项容器时,strict_types声明会被忽略吗?
$container = new League\Container\Container;
$container->add(Blog::class)->addArgument(7);
$foo = $container->get(Blog::class);
echo $foo->post();
// I passed `7` in the parameter, it doesn't work as expected
// because it should've fatal error with TypeError because `7` is not a string
对src
的{{1}}文件夹的快速浏览显示,该文件的所有文件也都使用league\container
。也就是说,我不确定容器是否有可能检测其启动的类的参数类型。如果不可能,那么在这种情况下使用declare(strict_types=1);
是没有用的吗?