面向对象特殊实践
(只有在php里面才有,其他语言面向对象没有)
面向对象--魔术方法
__construct(), __destruct() 构造函数和析构函数
__tostring()
__invoke()
__call(), __callstatic()
__get(), __set(), __isset(), __unset()
__clone()
__tostring()
当对象被当作string使用时,这个方法会被自动调用。
echo $obj;
__invoke()
当对象被当成方法调用时,这个方法会被自动调用
$obj(4);
output:
this is the class magictest.
__invoke called with parameter 5
__call()
当对象访问不存在的方法名称时,__call()方法会被自动调用
__callstatic()
当对象访问不存在的静态方法名称时,__callstatic()方法会被自动调用
这两个方法在php里面也被成为方法的重载(overloading)
注意区分重写(overwrite)
通过这两个方法,同一个方法的名称的调用可以对应不同的方法实现
runtest(para1,para2); //没有声明这个runtest方法,因为有__call这个魔术方法,也可以被调用magictest::runtest(para1,para2); //没有声明这个runtest方法,因为有__callstatic这个魔术方法,也可以被调用?>
output:
calling runtest with parameters: para1,para2
static calling runtest with parameters: para1,para2
__get(), __set(), __isset(), __unset()
在给不可访问属性赋值时,__set()会被调用
读取不可访问属性的值时,__get()会被调用
当对不可访问属性调用isset()或empty()时,__isset()会被调用
当对不可访问属性调用unset()时,__unset()会被调用
所谓不可访问属性,实际上就是在调用某个属性是发现这个属性没有被定义,这时候不同的操纵会触发不同的魔术方法
这几个方法也被称为属性重载的魔术方法
classname.\n; //classname未定义,但是通过魔术方法__get,这个方法好像被定义了一样$obj->classname='magicclassx'; //通过魔术方法__get将classname名称定义为magicclassxecho '$obj->name is set?'.isset($obj->classname).\n;echo '$obj->name is empty?'.empty($obj->classname).\n;unset($obj->classname);?>
output:
getting the property classname
setting the property classname to value magicclassx
__isset invoked
$obj->name is set?1 //如果return为true的话,结果显示为1;如果return为false的话,结果显示为空
__isset invoked
$obj->name is empty? //如果return为true的话,结果显示为空;如果return为false的话,结果显示为1
unsetting property classname
面向对象--魔术方法
__clone()
对象编程——特殊实践day 4>
name='tbd'; //屏蔽你不想要他复制过去的数据,屏蔽掉他的数据,设置他的初始值 }}$james = new nbaplayer();$james->name = 'james';echo $james->name.\n;$james2 = clone $james;echo before set up: james2's: .$james2->name.\n;$james2->name='james2';echo james's: .$james->name;echo james's: .$james2->name;?>
output:
james
before set up: james2's: tbd
james's: james
james's: james2 //james2的数据不会影响james的数据
-------------------------------------------------------------------------------php面向对象编程笔记就此完毕---------------------------------------------------------------------------------------
以上就介绍了php面向对象编程——特殊实践day 4,包括了方面的内容,希望对php教程有兴趣的朋友有所帮助。