您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

PHP 中__call()的使用方法

2024/5/22 7:24:22发布39次查看
php5 的对象新增了一个专用方法 __call(),这个方法用来监视一个对象中的其它方法。如果你试着调用一个对象中不存在或被权限控制中的方法,__call 方法将会被自动调用。
1.__call的使用
<?php class foo { function __call($name,$arguments) { print("did you call me? i'm $name!"); } } $x = new foo(); $x->dostuff(); $x->fancy_stuff(); ?>
2.使用 __call 实现“过载”动作
<?php class magic { function __call($name,$arguments) { if($name=='foo') { if(is_int($arguments[0])) $this->foo_for_int($arguments[0]); if(is_string($arguments[0])) $this->foo_for_string($arguments[0]); } } private function foo_for_int($x) { print("oh an int!"); } private function foo_for_string($x) { print("oh a string!"); } } $x = new magic(); $x->foo(3); $x->foo("3"); ?>
3._call和___callstatic这两个函数是php类 的默认函数,
__call() 在一个对象的上下文中,如果调用的方法不能访问,它将被触发
__callstatic() 在一个静态的上下文中,如果调用的方法不能访问,它将被触发
<?php abstract class obj { protected $property = array(); abstract protected function show(); public function __call($name,$value) { if(preg_match("/^set([a-z][a-z0-9]+)$/i",$name,$array)) { $this->property[$array[1]] = $value[0]; return; } elseif(preg_match("/^get([a-z][a-z0-9]+)$/i",$name,$array)) { return $this->property[$array[1]]; } else { exit("<br>;bad function name '$name' "); } } } class user extends obj { public function show() { print ("username: ".$this->property['username']."<br>;"); //print ("username: ".$this->getusername()."<br>;"); print ("sex: ".$this->property['sex']."<br>;"); print ("age: ".$this->property['age']."<br>;"); } } class car extends obj { public function show() { print ("model: ".$this->property['model']."<br>;"); print ("sum: ".$this->property['number'] * $this ->property['price']."<br>;"); } } $user = new user; $user ->setusername("anny"); $user ->setsex("girl"); $user ->setage(20); $user ->show(); print("<br>;<br>;"); $car = new car; $car ->setmodel("bw600"); $car ->setnumber(5); $car ->setprice(40000); $car ->show(); ?>
总结:
__call()函数是php类的默认魔法函数,__call() 在一个对象的上下文中,如果调用的方法不存在的时候,它将被触发。
相关推荐:
php中__call()和__callstatic()使用方法
php中__call()方法如何使用与重载实例分析
php的魔术方法__get(),__set(),__call(),__callstatic()以及static用法详解
魔术方法__call()实例详解(php面向对象高级教程)
以上就是php 中__call()的使用方法的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product