您好,欢迎访问一九零五行业门户网

php中类外部访问类私有属性的方法

我们都知道,类的私有属性在类外部是不可访问的,包括子类中也是不可访问的。比如如下代码:
_prop; };  $a = new example1(); var_dump($r($a));  //运行结果:fatal error: cannot access private property example1::$_prop ?> 
但某些情况下我们需要访问类的私有属性,有下面这么几种方法可以实现:
1.利用反射
_prop; };  $a = new example1(); $rfp = new reflectionproperty('example1','_prop'); $rfp->setaccessible(true); var_dump($rfp->getvalue($a));  //结果输出:string 'test' (length=4) ?> 
2.利用closure::bind()
此方法是php 5.4.0中新增的。
_prop; };  $a = new example1(); $r = closure::bind($r,null,$a);  var_dump($r($a));  //结果输出:string 'test' (length=4) ?> 
另外,我们也可以用引用的方式来访问,这样我们就可以修改类的私有属性:
_prop; }, null, $a);  $cake = & $r($a); $cake = 'lie'; var_dump($r($a));  //结果输出:string 'lie' (length=3) 
据此,我们可以封装一个函数来读取/设置类的私有属性:
$property;     }, $object, $object)->__invoke();      return $value; }; ?> 
closure::bind()还有一个很有用之处,我们可以利用这一特性来给一个类动态的添加方法。官方文档中给了这么一个例子:
methods[$methodname] = closure::bind($methodcallable, $this, get_class());     }          public function __call($methodname, array $args)     {         if (isset($this->methods[$methodname])) {             return call_user_func_array($this->methods[$methodname], $args);         }                  throw runtimeexception('there is no method with the given name to call');     }      }  class hackthursday {     use metatrait;          private $dayofweek = 'thursday';      }  $test = new hackthursday(); $test->addmethod(addedmethod,function(){     return '我是被动态添加进来的方法'; });  echo $test->addedmethod();  //结果输出:我是被动态添加进来的方法 ?>
以上就介绍了php中类外部访问类私有属性的方法,包括了方面的内容,希望对php教程有兴趣的朋友有所帮助。
其它类似信息

推荐信息