php使用面向对象魔术方法之__call函数:1、当调用一个不可以访问的成员方法时,【__call】魔术方法就会被调用;2、该成员方法不存在以及成员方法是protected或者private时,调用【__call】魔术方法。
php使用面向对象魔术方法之__call函数:
基本介绍:
(1) 当我们调了一个不可以访问的成员方法时,__call魔术方法就会被调用.
(2) 不可以访问的成员方法的是指(1. 该成员方法不存在, 2. 成员方法是protected或者 private)
需求
我们就是希望,在类的外部直接调用不可访问的成员方法(private , protected).
案例说明
<?php header('content-type:text/html;charset=utf-8'); //__call魔术方法 class monk{ public $name; protected $hobby; public function __construct($name, $hobby){ $this->name = $name; $this->hobby = $hobby; } //输出该对象的信息 public function showinfo(){ echo '<br> 名字是 ' . $this->name; foreach($this->hobby as $hobby){ echo '<br> 爱好有 ' . $hobby; } } //会做算术题, 保护的 protected function getsum($num1, $num2){ return $num1 $num2; } //编写这个__call魔术方法, __call 魔术方法会接收到两个参数 /* @param $method_name 就是函数名 @param $parameters 就是参数,类型是array */ public function __call($method_name, $parameters){ // echo '<br> method_name = ' . $method_name;// echo '<br> $parameters <br>';// var_dump($parameters); //判断 $this 中是否有 $method_name 函数,有就返回true,否则返回false if(method_exists($this, $method_name)){ return $this->$method_name($parameters[0], $parameters[1]); }else{ return '没有你要调用的函数'; } } } $monk = new monk('济公', array('no1'=>'腾云驾雾', 'no2'=>'喝酒')); $monk->showinfo(); //当我们直接调用 protected 方法时,就会触发 __call 魔术方法 echo '<br> 结果是' . $monk->getsum(100, 200);练习题:
<?php header('content-type:text/html;charset=utf-8'); /* 练习题: 请编写一个cat类(有 年龄, 名字 二个属性),要求二个属性全部都是public。cat类有一个 方法 jisuan($n1, $n2, $oper) 可以计算 - * / 是私有的.在类外部,$对象名->play('jisuan', $n1, $n2, $oper) 得到结果,注意play这个方法,在类中没有定义.要求 play 是固定的,如果没有按规则写,则给出相应的错误提示! */ class cat{ public $name; public $age; public function __construct($name, $age){ $this->name = $name; $this->age = $age; } private function jisuan($n1, $n2, $oper){ $res = 0; switch($oper){ case ' ': $res = $n1 $n2; break; case '-': $res = $n1 - $n2; break; case '*': $res = $n1 * $n2; break; case '/': $res = $n1 / $n2; break; default : echo '你输入的运算符号不对'; } return $res; } //编写一个__call 魔术方法 public function __call($method_name, $parameters){ //先判断是否通过 'play' 调用 if($method_name == 'play'){ //继续 if( method_exists($this, $parameters[0]) ){ //继续 return $this->$parameters[0]($parameters[1], $parameters[2], $parameters[3]); }else{ return ' 你调用的 ' . $parameters[0] . ' 不存在'; } }else{ return ' 你调用的方式有问题 '; } } } $cat = new cat('小花猫', 3); echo '<br> 运算的结果是 ' . $cat->play('jisuan', 10, 20, '-');
优惠云服务器近期价格下降应急手机号使用人为天津 小蚂蚁搬家服务中心员工赵伟网页跳转问题-云服务器问题腾讯云服务器如何搭建挂机宝SketchUp图层在哪里 SketchUp图层管理工具介绍腾讯云服务器建站教程7云端与云端服务器的区别多枚域名结拍 ew.cc拍出大五位