PHP 常见的魔术方法
__get() / __set() ———————— 主要用来接管对象的属性
<?php namespace Bpp; class Object { protected $arr = []; public function __get($key) { return $this->arr[$key]; } public function __set($key , $value) { $this->arr[$key] = $value; return 'ok'; } } $object = new Object(); echo $object->title="hello"; echo $object->title;
__call __callStatic ———————— 控制方法调用
class Object { protected $arr = []; public function __get($key) { return $this->arr[$key]; } public function __set($key , $value) { $this->arr[$key] = $value; } public function __call($func, $params) { var_dump($func , $params); echo "you call funcname is $func "; } public static function __callStatic($name, $arguments) { echo "call static function name is $name"; } } $object = new Object(); $object->hello('lufy','12age'); $object::say();
__toString() ———————————— 转化对象为字符串
<?php class Object { protected $arr = []; public function __get($key) { return $this->$arr[$key]; } public function __set($key , $value) { $this->$arr[$key] = $value; return 'ok'; } public function __toString() { return __CLASS__; } } $obj = new object(); echo $obj;
__invoke() —————————————— 将字符串当作函数来执
<?php class Object { protected $arr = []; public function __get($key) { return $this->$arr[$key]; } public function __set($key , $value) { $this->$arr[$key] = $value; return 'ok'; } public function __toString() { return __CLASS__; } public function sayHi() { echo 'sayHi'; } public function __invoke($param) { var_dump($param); } } $obj = new Object(); $obj("hello");

浙公网安备 33010602011771号