PHP的重载使用魔术方法代码实例详解 |
摘录PHP官网对PHP重载的解释:PHP所提供的"重载"(overloading)是指动态地"创建"类属性和方法 。我们是通过魔术方法(magic methods)来实现的 。 Note: Note: 属性重载public __set ( string $name , mixed $value ) : void public __get ( string $name ) : mixed public __isset ( string $name ) : bool public __unset ( string $name ) : void 在给不可访问属性赋值时,__set() 会被调用 。 Note: Note: Example #1 使用 __get(),__set(),__isset() 和 __unset() 进行属性重载 class PropertyTest { /** 被重载的数据保存在此 */ private $data = array(); /** 重载不能被用在已经定义的属性 */ public $declared = 1; /** 只有从类外部访问这个属性时,重载才会发生 */ private $hidden = 2; public function __set ($name, $value) { $this->data[$name] = $value; } public function __get ($name) { if (isset($this->$name)) { return $this->$name; } if (array_key_exists($name, $this->data)) { return $this->data[$name]; } //产生一条回溯跟踪 $trace = debug_backtrace(); //抛出异常 trigger_error('Undefined property via __get(): ' . $name . ' in ' . $trace[0]['file'] . ' on line ' . $trace[0]['line'], E_USER_NOTICE); return null; } public function __isset ($name) { return isset($this->data[$name]); } public function __unset ($name) { unset($this->data[$name]); } /** 非魔术方法 */ public function getHidden () { return $this->hidden; } } $obj = new PropertyTest; //输出不存在的a变量,走到__get()中,会抛出异常 echo $obj->a; //对不存在的a变量赋值为1,会走到__set()中 $obj->a = 1; //再次输出a变量,由于上面已经对其__set(),所以这是可以访问到a的值为1 echo $obj->a; //此时使用isset()对不存在的a变量进行运算时,会走到__isset()中,由于上面已经对其__set(),所以是true var_dump(isset($obj->a)); //对a进行unset()时,会走到__unset()中 unset($obj->a); //再对其进行isset(),此时已经不存在了 var_dump(isset($obj->a)); //访问private 属性的变量,会进入__get()中 echo $obj->hidden; 方法重载public __call ( string $name , array $arguments ) : mixed public static __callStatic ( string $name , array $arguments ) : mixed 在对象中调用一个不可访问方法时,__call() 会被调用 。 Example #2 使用 __call() 和 __callStatic() 对方法重载 class MethodTest { /** * 调用不存在的方法时进入此处 * @param $name * @param $arguments */ public function __call ($name, $arguments) { // 注意: $name 的值区分大小写 $info = [ 'name' => $name, 'arguments' => $arguments, ]; print_r($info); } /** * PHP 5.3.0之后版本 * 调用不存在的静态方法时,进入此处 */ public static function __callStatic ($name, $arguments) { // 注意: $name 的值区分大小写 $info = [ 'name' => $name, 'arguments' => $arguments, ]; print_r($info); } } $arguments = ['A', 'B', 'C']; $obj = new MethodTest; $obj->test(...$arguments); MethodTest::test(...$arguments); // PHP 5.3.0之后版本 /* * 以上两个都输出: * Array ( [name] => test [arguments] => Array ( [0] => A [1] => B [2] => C ) ) */ 到此这篇关于PHP的重载使用魔术方法代码实例详解的文章就介绍到这了,更多相关PHP的重载使用魔术方法内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家! |