<?php
abstract class AbstractClass
{
public function __get($theName)
{
return (isset($this->$theName)) ? $this->$theName : NULL;
}
public function __set($theName, $theValue)
{
if (false === property_exists(get_class(), $theName)) {
throw new Exception(get_class()." does not have '".$theName."' property.");
} else {
$this->$theName = $theValue;
}
}
}
class ConcreteClass extends AbstractClass
{
private $x;
private $y;
public function __construct($theX, $theY)
{
$this->x = $theX;
$this->y = $theY;
}
}
$concreteClass = new ConcreteClass(10, 20);
var_dump( $concreteClass->x );
有什么方法可以完成这项工作,还是我必须将这些神奇方法添加到扩展类中?
这会起作用:
public function __get($theName)
{
if(property_exists($this, $theName)) {
$reflection = new ReflectionProperty($this, $theName);
$reflection->setAccessible($theName);
return $reflection->getValue($this);
}
}
IMO,你不应该使用__get
and __set
作为 getter 和 setter 的替代品。由于它们在尝试访问不可访问的属性时被触发,因此它们与错误处理更相关。而且它们也比常规的 getter 或 setter 慢得多。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)