如何在没有参数的情况下调用类型提示的 php 函数


How to call a type hinted php function without parameter

我有一个php函数:

function myFunc(MyClass inst) {
    // ...
}

有时,当我调用此函数时,我不想传递任何参数,但这不起作用:

myFunc(null);

错误消息是:

... must be an instance of MyClass , null given

通过提供默认值,使函数的参数可选。所以而不是

function myFunc(MyClass inst)

它应该是

function myFunc(MyClass inst=null)

查看文档 http://php.net/manual/en/functions.arguments.php

只需像这样放置默认的初始值设定项:

function myFunc(MyClass inst=null) {
    // ...
}

然后,如果您不想传递参数,请调用它而不传递参数:D