PHP5 之 __set()和__get() 函数

PHP5 之 __set()和__get() 函数
  1. class TestMagicFun{
  2.      public $name = '';
  3.      public $email = '';
  4. }
  5. $testObj = new TestMagicFun();
  6. $testObj->name = 'simple';
  7. $testObj->email = 'abc@gmail.com';
  8. $testObj->address = 'earth china';
  9. 下面的代码在php4,php5中运行都无问题,而在实际的工作中,我们可能不想使用者对未声明的属性进行赋值,此时PHP4就无能为力了,还好在PHP5中有__set(),__get()这样的魔法方法可以用。
  10. 我们可以对上面的类进行一下改造
  11. class TestMagicFun{
  12.      public $name = '';
  13.      public $email = '';
  14.      
  15.      private function __set($property,$value)
  16.      {
  17.          // 在此处做一些特殊的处理
  18.          print "not defined {$property}";
  19.      }
  20.      
  21.      private function __get($property)
  22.      { 
  23.           // 在此处做一些特殊的处理
  24.          print "not defined {$property}";
  25.      }
  26. }
  27. 然后再初始化一个对像
  28. $testObj = new TestMagicFun();
  29. $testObj->name = 'simple';
  30. $testObj->email = 'abc@gmail.com';
  31. $testObj->address = 'earth china';

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值