这是一种基于访问器的方法:
class Extendible
{
private $properties;
public function extend(array $properties)
{
foreach ($properties as $name => $value) {
$this->properties[$name] = $value;
}
}
public function __call($method, $parameters)
{
$accessor = substr($method, 0, 3);
$property = lcfirst(substr($method, 3));
if (($accessor !== 'get' && $accessor !== 'set')
|| !isset($this->properties[$property])) {
throw new Exception('No such method!');
}
switch ($accessor) {
case 'get':
return $this->getProperty($property);
break;
case 'set':
return $this->setProperty($property, $parameters[0]);
break;
}
}
private function getProperty($name)
{
return $this->properties[$name];
}
private function setProperty($name, $value)
{
$this->properties[$name] = $value;
return $this;
}
}
演示:
try {
$x = new Extendible();
$x->extend(array('foo' => 'bar'));
echo $x->getFoo(), PHP_EOL; // Shows 'bar'
$x->setFoo('baz');
echo $x->getFoo(), PHP_EOL; // Shows 'baz'
echo $x->getQuux(), PHP_EOL; // Throws Exception
} catch (Exception $e) {
echo 'Error: ', $e->getMessage(), PHP_EOL;
}