call_user_func()注意事项

php中in_array()函数使用注意事项:

函数原型:       

bool in_array ( mixed needle, array haystack [, bool strict] )
    
    在 haystack 中搜索 needle,如果找到则返回 TRUE,否则返回 FALSE.
    
    如果第三个参数 strict 的值为 TRUE 则 in_array() 函数还会检查 needle 的类型是否和 haystack 中的相同
    
    其实最关键的还是因为php是弱类型的语言,在使用in_array()的时候最好还是加上strict参数。因为这样不但比较两者的值是否一直,还会比较两者的类型是否一直。
    
    另外,我们在控制结构比较两个数值是否一直的时候,也应该尽量使用 === 来代替 ==(当然,这个也根据具体的业务逻辑选用比较合适的)。
    
    下面解释一下为什么
    
    var_dump(in_array(0, array(‘s' ));
    
    这句话的结果是bool(true)。
    
    因为in_array会将0 和's' 进行比较,0是number类型,'s’是string类型,根据php manual 中“Comparison Operators” 一章的说明可知,number 和string进行比较的时候,会先将string类型首先转化为number,然后再进行比较操作。 's‘转化为number的结果为0,而0 == 0 的结果是true,所以in_array(0, array('s', 'ss’))的结果也是true;
    
    如果把in_array 的第三个参数strict设置为 true,比较的时候 就会判断值和类型是否都相当。如果都相当的话,才会返回true,否则返回false。

 

 

 


 

 

(PHP 4, PHP 5, PHP 7)

call_user_func — 把第一个参数作为回调函数调用

说明

call_user_func ( callable $callback [, mixed $parameter [, mixed $... ]] ) : mixed

第一个参数 callback 是被调用的回调函数,其余参数是回调函数的参数。

参数

 

callback

将被调用的回调函数(callable)。

parameter

0个或以上的参数,被传入回调函数。

Note:

请注意,传入call_user_func()的参数不能为引用传递。

Example #1 call_user_func() 的参考例子

<?php
error_reporting(E_ALL);
function increment(&$var)
{
    $var++;
}

$a = 0;
call_user_func('increment', $a);
echo $a."\n";

call_user_func_array('increment', array(&$a)); // You can use this instead before PHP 5.3
echo $a."\n";
?>

以上例程会输出:

0
1

 

 

返回值

返回回调函数的返回值。

更新日志

 

版本说明
5.3.0 对面向对象里面的关键字的解析有所增强。在此之前,使用两个冒号来连接一个类和里面的一个方法,把它作为参数来作为回调函数的话,将会发出一个E_STRICT的警告,因为这个传入的参数被视为静态方法。

 

范例

 

Example #2 call_user_func() 的例子

<?php
function barber($type)
{
    echo "You wanted a $type haircut, no problem\n";
}
call_user_func('barber', "mushroom");
call_user_func('barber', "shave");
?>

以上例程会输出:

You wanted a mushroom haircut, no problem
You wanted a shave haircut, no problem

Example #3 call_user_func() 命名空间的使用

<?php

namespace Foobar;

class Foo {
    static public function test() {
        print "Hello world!\n";
    }
}

call_user_func(__NAMESPACE__ .'\Foo::test'); // As of PHP 5.3.0
call_user_func(array(__NAMESPACE__ .'\Foo', 'test')); // As of PHP 5.3.0

?>

以上例程会输出:

Hello world!
Hello world!

Example #4 用call_user_func()来调用一个类里面的方法

<?php

class myclass {
    static function say_hello()
    {
        echo "Hello!\n";
    }
}

$classname = "myclass";

call_user_func(array($classname, 'say_hello'));
call_user_func($classname .'::say_hello'); // As of 5.2.3

$myobject = new myclass();

call_user_func(array($myobject, 'say_hello'));

?>

以上例程会输出:

Hello!
Hello!
Hello!

Example #5 把完整的函数作为回调传入call_user_func()

<?php
call_user_func(function($arg) { print "[$arg]\n"; }, 'test'); /* As of PHP 5.3.0 */
?>

以上例程会输出:

[test]

 

注释

Note:

在函数中注册有多个回调内容时(如使用 call_user_func() 与 call_user_func_array()),如在前一个回调中有未捕获的异常,其后的将不再被调用。

 

 

参考

https://xz.aliyun.com/t/2451

posted @ 2019-08-03 14:49  壹個人坐在角落  阅读(182)  评论(0编辑  收藏  举报