PHP魔术方法的的理解

_set:属性不存在时自动设置属性

/**
* 属性不存在时通过__set自动设置属性
* @param $key [键名]
* @param $value [属性值]
*/
function __set($key,$value){
$this->arr[$key] = $value;
}

代码:
$object->title = 'blue'; //设置不存在的属性,调用__set()
echo $object->title,'<br/>'; //输出不存在的属性,调用__get()

输出:
blue

__get:属性不存在或不能读取时,设置该方法可读取

/**
* 属性不存在或不能读取(属性为私有private)时,通过__get读取
* @param $key 键名
* @return 属性
*/
function __get($key){
return $this->arr[$key];
}

__call:方法不存在时,执行

/**
* 方法不存在时,执行__call方法
* @param $func [方法名]
* @param $param [参数]
* @return [description]
*/
function __call($func,$param){
var_dump($func);
echo '<br/>';
var_dump($param);
echo '<br/>';
}

代码:
$object -> show('hello','world'); //调用不存在的方法,调用__call()

输出:
string(4) "show"
array(2) { [0]=> string(5) "hello" [1]=> string(5) "world" }

__callStatic:静态方法不存在时,执行

/**
* 静态方法不存在时,执行__callStatic方法
* @param $func [方法名]
* @param $param [参数]
* @return [description]
*/
static function __callStatic($func,$param){
var_dump($func);
echo '<br/>';
var_dump($param);
echo '<br/>';
}

代码:
IMooc\Object::show('hello','world'); //调用不存在的静态方法,调用__callStatic()

输出:
string(4) "show"
array(2) { [0]=> string(5) "hello"  [1]=>string(5) "world" }

__toString:当对象转换为字符串时,执行

/**
* 当对象转换为字符串时,执行__toString方法
* @return string [description]
*/
function __toString{
return __CLASS__;
}

代码:
echo $object,'<br/>'; //将对象以字符串形式输出,调用__toString()

输出:
IMooc\Object

__invoke:当把对象当成函数来使用时,执行

/**
* 当把对象当成函数来使用时,执行__invoke方法
* @param [type] $param [参数]
* @return [type] [description]
*/
function __invoke($param){
var_dump($param);
}

代码:
echo $object('hello'); //将对象当函数使用,调用__invoke()

输出:
string(5) "hello"


链接:https://www.imooc.com/article/13239
 

猜你喜欢

转载自blog.csdn.net/oJingZhiYuan12/article/details/86527130