当参数为数组或可调用时如何执行函数?
How to execute function when parameter is array or callable?
看这个示例代码:
我遇到错误:
Fatal error: Uncaught Error: Cannot use object of type Closure as array in C:\xampp\htdocs\dermaquality\test.php:11 Stack trace: #0 C:\xampp\htdocs\dermaquality\test.php(20): test(Object(Closure)) #1 {main} thrown in
$array = array(
'hello' => function() {
echo "HEllo world";
}
);
function test( $func )
{
if (is_callable( $func['hello'] )) {
$func['hello']();
}
else {
$func();
}
}
echo "Executing 1 <br/>";
test( $hello = function() {"Hello world";} );
echo "Executing 2 <br/>";
test( $array['hello'] );
exit;
如果 $func
是函数或 $func['hello']
是函数,我如何调用 $func
?
谢谢。
问题出在 if (is_callable( $func['hello'] )) {
中,因为您不知道 $func
是否是一个数组。顺便说一句,您没有将数组作为参数放入 test( $array['hello'] );
中,您只是将函数...
function test( $func )
{
if (is_callable($func)) {
$func();
}
else if (is_array($func)){
if(isset($func['hello']) && is_callable($func['hello'])){
$func['hello']();
}else{
// unknown what to call
}
}else{
// unknown what to call
}
}
看这个示例代码:
我遇到错误:
Fatal error: Uncaught Error: Cannot use object of type Closure as array in C:\xampp\htdocs\dermaquality\test.php:11 Stack trace: #0 C:\xampp\htdocs\dermaquality\test.php(20): test(Object(Closure)) #1 {main} thrown in
$array = array(
'hello' => function() {
echo "HEllo world";
}
);
function test( $func )
{
if (is_callable( $func['hello'] )) {
$func['hello']();
}
else {
$func();
}
}
echo "Executing 1 <br/>";
test( $hello = function() {"Hello world";} );
echo "Executing 2 <br/>";
test( $array['hello'] );
exit;
如果 $func
是函数或 $func['hello']
是函数,我如何调用 $func
?
谢谢。
问题出在 if (is_callable( $func['hello'] )) {
中,因为您不知道 $func
是否是一个数组。顺便说一句,您没有将数组作为参数放入 test( $array['hello'] );
中,您只是将函数...
function test( $func )
{
if (is_callable($func)) {
$func();
}
else if (is_array($func)){
if(isset($func['hello']) && is_callable($func['hello'])){
$func['hello']();
}else{
// unknown what to call
}
}else{
// unknown what to call
}
}