我想有一个接受参数A
的PHP函数,该函数已给出类型提示callable
。在某些情况下,我希望能够将NULL
或类似的内容作为参数值传递,表示未提供回调。我收到以下错误:
"Argument must be callable, NULL given".
有什么想法可以实现这一点吗?
回应发布的答案和问题...
PHP版本是5.4.14
代码是...
class DB
{
protected function ExecuteReal($sqlStr, array $replacements, callable $userFunc, $allowSensitiveKeyword)
{
...
if( $userFunc != NULL && is_callable($userFunc) )
$returnResult = $call_user_func($userFunc, $currRow);
...
}
...
public function DoSomething(...)
{
$result = $this->ExecuteReal($queryStr, Array(), NULL, TRUE);
...
}
}
在上面的代码片段中,我不需要使用任何数据进行回调,因此,无需传递可调用对象,而只需传递NULL。但这是导致错误消息的原因。
解决方案是下面的答案...谢谢大家:)
[当您使用类型提示时(只有array
interface
s和class
es可以被类型提示/ till php 5.6/。/自7.0起,也可以键入提示标量类型/),可以将参数的默认值设置为null。如果需要,请将该参数设为可选。
$something = 'is_numeric';
$nothing = null;
function myFunction(Callable $c = null){
//do whatever
}
所有作品:
myFunction();
myFunction($nothing);
myFunction($something);
在此处阅读更多:http://php.net/manual/en/language.oop5.typehinting.php
您只能键入提示对象和数组。如果像下面这样声明函数,则类型提示变量可以为null:
function aFn($required, MyCallable $optional=null){ /*do stuff */}
其中MyCallable
是类名或关键字Array
。