我想使用魔术方法 __get($property) 和 __set($property, $value) 而不是每个属性的单独方法。有可能吗,如果有,怎么做?
你不应该定义每个属性。一个简单的数组容器对他们来说就足够了。所以,这正是您正在寻找的:
class Foo
{
private $container = array();
public function __set($property, $value)
{
$this->container[$property] = $value;
}
public function __get($property)
{
if (array_key_exists($property, $this->container)){
return $this->container[$property];
} else {
trigger_error(sprintf('Undefined property "%s"', $property));
}
}
}
$foo = new Foo();
$foo->bar = "123";
print $foo->bar; // prints 123
$foo->id = "test string";
print $foo->id; // test string
print $foo->nonExistingProp; //issues E_NOTICE
如果您坚持使用访问器/修饰符,那么您只需要重载它们。使用__call()
class Foo
{
private $container = array();
public function __call($method, array $args)
{
$property = substr($method, 3);
if (substr($method, 0, 3) == 'get'){
// getter is being used
if (isset($this->container[$property])){
return $this->container[$property];
}
}
if (substr($method, 0, 3) == 'set'){
//setter is being used
$this->container[$property] = $args[0];
}
}
}
$foo = new Foo();
$foo->setId('__BAR__');
$foo->setStuff('__YEAH__');
print $foo->getId(); // prints __BAR__
print $foo->getStuff(); //prints __YEAH__