php的魔术方法(转)
从php5以后的版本,类就可以使用魔术方法了。php规定以两个下划线(__)开头的方法都保留为魔术方法,所以建议大家函数名最好不用__开头,除非是为了重载已有的魔术方法。
目前php已有的魔术方法有__construct,__destruct,__call,__get,__set,__isset,__unset,__sleep,__wakeup,__toString,__set_state 和 __clone。
__construct和__destruct是类的构造函数和析构函数,这个大家经常会用到,相信大家都很熟悉,这里就不多说了。
__sleep和__wakeup是序列化类的时候调用的。当序列化对象时,php将试图在序列动作之前调用该对象的成员函数__sleep(),当使用unserialize() 恢复对象时, 将调用__wakeup()。
__toString是对象被转为string时调用的,例如
view plaincopy to clipboardprint? 01.
上例将输出 Hello
__set_state是当用var_export()来导出类的时候调用的,这个魔术函数只有一个参数,这个参数是一个数组,用来指定export的时候得到的属性。一般很少用到。
__call, __get和__set 这三个魔术方法是最常用的,当调用类中不存在的方法时就会调用__call,而__get和__set则是访问和设置类不存在的成员变量时调用的。 这三个的函数原型如下:
view plaincopy to clipboardprint?
01.mixed __call(string $name, array $arguments)
02.void __set(string $name, mixed $value)
03.mixed __get(string $name)
mixed __call(string $name, array $arguments)
void __set(string $name, mixed $value)
mixed __get(string $name)
__call的例子:
view plaincopy to clipboardprint? 01.
上例将输出: Method test called: Array ( [0] => 1 [1] => 2 )
__get 和 __set 的例子:
view plaincopy to clipboardprint? 01.
上例将输出: b 1 The value of b is 1
__isset和__unset这两个与__get和__set其实原理是差不多的,他们的原型如下:
view plaincopy to clipboardprint?
01.bool __isset(string $name)
02.void __unset(string $name)
bool __isset(string $name)
void __unset(string $name)
举个例子:
view plaincopy to clipboardprint? 01.
上例将输出: bool(true) bool(true) object(a)#1 (2) { ["c"]=> int(3) ["arr"]=> array(1) { ["a"]=> int(1) } }
类复制(clone)的时候,如果有定义__clone这个魔术方法就会调用它。 举例如下:
view plaincopy to clipboardprint? 01.