我有一个简单的类,其中1个方法接受一个参数.
class ArticleController
{
public function show(Article $article)
{
// some logic here
}
}
Run Code Online (Sandbox Code Playgroud)
我想以这种方式使用它:
$articleController = new ArticleController;
$articleController->show();
Run Code Online (Sandbox Code Playgroud)
如你所见,我没有将任何值传递给方法"show".但是因为php7已经出来并且它强制传递该值(依赖性),有没有什么方法我不会将该值传递给该方法并且仍然可以使用它而没有错误?我的PHP版本= 7.1.8
问题中描述的行为并不特定于PHP 7.它在PHP 5上也是如此.
您可以为参数设置默认值$article(以这种方式使其可选)但如果将其设置为NULL则必须确保在方法中正确处理该值:
class ArticleController
{
public function show(Article $article = NULL)
{
if (isset($article)) {
// some logic here, $article is an object
} else {
// $article is NULL, cannot use it as an object
}
}
}
Run Code Online (Sandbox Code Playgroud)
当您调用show()而不传递值时,将$article使用默认值(NULL在此示例中)初始化参数.
$controller = new ArticleController();
$news = new Article();
$controller->show($news);
// inside the show() method, $article is set to $news
$controller->show();
// no argument was passed, $article is NULL inside show()
Run Code Online (Sandbox Code Playgroud)