[PHP] 在PHP类中对属性实现类似final →→→→→进入此内容的聊天室

来自 , 2021-04-12, 写在 PHP, 查看 169 次.
URL http://www.code666.cn/view/09d37c08
  1. <?php
  2. class a {
  3.     public $attr = 'a';
  4.    
  5.     public $x = 'q';
  6. }
  7.  
  8. class b extends a {
  9.     public $abc = 'b';
  10.     public $attr = 'bc';    
  11.    
  12.     public function getVar($var){
  13.         $reflect = new ReflectionObject($this);
  14.         $properties = (array)$reflect->getProperties();
  15.         $parent = $reflect->getParentClass();
  16.        
  17.         $parent_reflect = new ReflectionObject(new $parent->name());
  18.         $parent_properties = $parent_reflect->getProperties();
  19.         if($reflect){
  20.             foreach($properties as $property){
  21.                 foreach($parent_properties as $parent_property){
  22.                     if($property->name == $var && $property->class == $reflect->getName() && $parent_property->name == $var){
  23.                         trigger_error($var . ' is finnal property');
  24.                         return false;
  25.                     }
  26.                 }
  27.             }
  28.         }
  29.        
  30.         if(!$reflect->hasProperty($var)){
  31.             trigger_error('Undefined property:' . $var);
  32.         }else{
  33.             return $this->$var;
  34.         }
  35.     }
  36. }
  37.  
  38. $a = new b();
  39. echo $a->getVar('attr');

回复 "在PHP类中对属性实现类似final"

这儿你可以回复上面这条便签

captcha