Php 类型提示和静态方法
当我运行此代码时Php 类型提示和静态方法,php,class,oop,static-methods,Php,Class,Oop,Static Methods,当我运行此代码时 class Kernel { private $settings = array(); public function handle(Settings $conf) { $this->settings = $conf; return $this; } public function run() { var_dump($this->settings); } }
class Kernel
{
private $settings = array();
public function handle(Settings $conf)
{
$this->settings = $conf;
return $this;
}
public function run()
{
var_dump($this->settings);
}
}
class Settings
{
public static function appConfig()
{
return array(
'database' => array(
'hostname' => 'localhost',
'username' => 'root',
'password' => 'test',
'database' => 'testdb'
)
);
}
}
$kernel = new Kernel;
$kernel->handle(Settings::appConfig())->run();
我犯了一个错误
Catchable fatal error: Argument 1 passed to Kernel::handle() must be an instance of Settings, array given, called in....
这是否意味着类型暗示只适用于实例,而不适用于静态方法?如果现在如何实现静态方法的类型提示?那么,错误文本将对此进行解释。 您正在此处传递一个数组:
$kernel->handle(Settings::appConfig())->run();
因为您的Settings::appConfig()
方法返回一个数组。
您必须在那里传递一个实例。$conf需要是设置对象的实例,以防止出现错误 handle methods类提示意味着只接受Settings类的对象实例。如果要将数组与handle方法一起使用,则需要进行此更改
public function handle(Settings $conf)
到
这将有助于:
public function handle(array $conf)
{
$this->settings = $conf;
return $this;
}
handle()
需要类Settings
的对象,但您只是提供了一个简单数组(appConfig()的返回值)。appConfig的返回值不是类设置的实例,您不能为想要获取类型设置的方法提供类型数组
public function handle(array $conf)
{
$this->settings = $conf;
return $this;
}