PHP5 之 __set()和__get() 函数
- classTestMagicFun{
- public$name='';
- public$email='';
- }
- $testObj=newTestMagicFun();
- $testObj->name='simple';
- $testObj->email='abc@gmail.com';
- $testObj->address='earthchina';
- 下面的代码在php4,php5中运行都无问题,而在实际的工作中,我们可能不想使用者对未声明的属性进行赋值,此时PHP4就无能为力了,还好在PHP5中有__set(),__get()这样的魔法方法可以用。
- 我们可以对上面的类进行一下改造
- classTestMagicFun{
- public$name='';
- public$email='';
- privatefunction__set($property,$value)
- {
- //在此处做一些特殊的处理
- print"notdefined{$property}";
- }
- privatefunction__get($property)
- {
- //在此处做一些特殊的处理
- print"notdefined{$property}";
- }
- }
- 然后再初始化一个对像
- $testObj=newTestMagicFun();
- $testObj->name='simple';
- $testObj->email='abc@gmail.com';
- $testObj->address='earthchina';