您的位置:首页 > 编程语言 > PHP开发

php的魔法方法__call使用

2012-07-17 15:50 274 查看
<?php

class Car
{
public function __call($method,$args)
{
print "method $method called\n";
var_dump($args);
}

/* 新版本php提供
public static function __callStatic($method,$args)
{
print "static method $method called\n";
var_dump($args);
}
*/
}

$car = new Car();
$car->run();
// method run called array(0) { }

$a = 100;
$car->run($a);
// method run called array(1) { [0]=> int(100) }

$a = array(
"a",
"b" => array(
1,2,3
),
"c"
);
$car->run($a);
// method run called array(1) { [0]=> array(3)
// { [0]=> string(1) "a" ["b"]=> array(3) {
// [0]=> int(1) [1]=> int(2) [2]=> int(3) }
// [1]=> string(1) "c" } }

$car = new Car();
$car->run("hello","world");
// method run called array(2) { [0]=> string(5) "hello" [1]=> string(5) "world" }

/*
$car::alarm();
*/
?>
可以看出调用不存在的方法时,不会抛错“call method undefined”,而是进入到我们定义的__call魔法函数,第一个参数$method为出错的函数名,$args为传递给这个函数的参数。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: