批改状态:合格
老师批语:这些拦截器, 是有点难的
<?phpabstract class creat1{public static function creat(){return new static();}}// 工作类1class User extends creat1{// 把原来的方法迁移到父类}// 工作类2class Prod extends creat1{// 把原来的方法迁移到父类}$user = new User();var_dump($user);echo '<br>';$prod = new Prod();var_dump($prod);
实例效果
<?php// 实例演示属性重载/拦截器的所有方法// 访问: 包括二个操作:就是读和写, 或者称为: 查询和设置// 属性拦截器: __set(), __get(), __isset(), __unset()class Goods{private $name;private $price;private $tax = 0.06;public function __construct($name,$price){$this->name = $name;$this->price = $price;}// 1. 属性查询拦截器public function __get($property){// a.先事先约定一些方法专用于处理属性访问:取出方法的名称$method = 'get'.ucfirst($property);// b. 根据方法的名称,转发访问请求return method_exists($this , $method) ? $this->$method() : null;}private function getname(){return $this->name;}private function getprice(){return $this->price;}// 2. 属性设置拦截器public function __set($prop , $value ){$meth = 'set'. ucfirst($prop);return method_exists($this , $meth) ? $this->$meth($value) : null;}private function setname($value){$this->name = $value;}private function setprice($value){$this->price = $value;}// 3. 属性检测拦截器public function __isset($prop){// $meth = 'isset'. ucfirst($prop);return $prop === 'name' ? isset($this->name) : false;}// 4. 属性销毁拦截器public function __unset($prop){$meth = 'unset'. ucfirst($prop);return method_exists($this , $meth) ? $this->$meth() : null;}}// 客户端// 创建对象,并初始化$goods = new Goods('十年普洱茶',1999);echo $goods->name . '的价格:' . $goods->price,'元','<br>';$goods->name = '今年的普洱茶';$goods->price = 30;echo $goods->name . '的价格:' . $goods->price,'元','<br>';echo isset($goods->name) ? '货物存在;' : '货物不存在;' ;echo isset($goods->price) ? '价格存在' : '价格不存在' . '<br>';unset($goods->name);echo $goods->name,'<br>';unset($goods->price);echo $goods->price,'<br>';
实例效果
<?phpclass User{// 方法拦截器public function __call($name, $arguments){printf('方法名: %s , 参数: [%s]',$name , implode(',', $arguments) );}// 静态方法拦截器public static function __callStatic($name, $arguments){printf('方法名: %s , 参数: [%s]',$name , implode(',', $arguments) );}}// 客户端$user = new User();$user->demo(1,2,3);echo '<br>';$user::demo(6,7,8);
实例效果
总结:
1.后期静态绑定工作在静态继承上下文中,定义类和调用类的绑定分开。self与定义类绑定,static与调用类绑定。
2.属性重载/拦截器
当访问一个不存在或者无权限访问的属性时,自动调用拦截器。
set()、get()、isset()、unset()
虽然理解它的原理,但是实现的代码有点陌生,希望日后慢慢熟悉。
3.方法重载/拦截器
call()、callstatic()
比属性拦截更有用。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号