php _call与__callStatic方法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cjqh_hao/article/details/81151536

php 5.3后新增__call与__callStatic魔法方法。
__call:当调用一个不可访问方法,会自动调用__call 方法。
__callStatic:在静态上下文中调用一个不可访问方法时,会自动调用__callStatic方法。

public mixed __call ( string $name, array $arguments )

public static mixed __callStatic ( string $name , array $arguments )

其中:
name 参数是要调用的方法名称。
arguments 参数是一个枚举数组,包含着要传递给name方法的参数列表。

class Person{

    public function __call($method, $arguments) {
        var_dump($method);
        echo "__call \n";
        var_dump($arguments);
    }

     public static function __callStatic($method, $arguments) {
        var_dump($method);
        echo "__callStatic \n";
        var_dump($arguments);
     }
}

$p = new Person;
echo Person::hello3(1);
/*
string(6) "hello3"
__callStatic 
array(1) {
  [0]=>
  int(1)
}
*/
echo $p->hello1(1);
/*
string(6) "hello1"
__call 
array(1) {
  [0]=>
  int(1)
}*/

Laravel5 框架中的Facade门面就是基于此实现的,提供了一个快捷访问类方法的方式。类是从容器中实例化而来,对应的方法最终是通过php __callStatic魔术方法实现,比如Cache::get();

猜你喜欢

转载自blog.csdn.net/cjqh_hao/article/details/81151536