我正在查看有关创建模型类的 Doctrine 2 和 Symfony 文档。有几个代码片段在类中使用了 getProperty 和 setProperty,当将值直接分配给属性时,它们会以某种方式自动使用.这与典型的 get/set 魔法方法不同,我遇到的示例代码没有实现任何自定义魔法方法,所以我相信这是由 Doctrine 某处处理的。
据我所知,Doctrine 实现了访问器和修改器。也许我在下载 Pear 时错过了一个包,或者我的脚本中没有包含某些东西。
例如:
class User {
public $name;
public function getName()
{
// Do stuff
}
}
$user = new User();
$foo = $user->name; // getName is called
注意:我正在寻找 Doctrine 特定的解决方案。我知道这可以通过 PHP 以某种方式完成,但我想使用 Doctrine 的本地函数。
编辑:更新以阐明这与典型的 get/set 魔术方法有何不同,并注意。
最佳答案
class User {
private $name;
public function __get($property) {
$methodName = "get".ucfirst($property);
if (method_exists($this, $methodName)) {
return call_user_func(array($this, $methodName));
} elseif (isset($this->{$property})) {
return $this->{$property};
}
return null;
}
public function __set($property, $value) {
$methodName = "set".ucfirst($property);
if (method_exists($this, $methodName)) {
call_user_func_array(array($this,$methodName), array($value));
} else {
$this->{$property} = $value;
}
}
public function getName() {
return "My name is ".$this->name;
}
}
$user = new User();
$user->name = "Foo";
$bar = $user->name;
echo $bar; // "My name is Foo"
如果有方法 getSomething
或 setSomething
直接访问属性时会调用它。
正如我在 this documentation page 中读到的那样,这正是上面的代码所做的 Doctrine 所做的。但它调用方法 _set('fieldName', 'value')
。
关于php - 自动 Getter/Setter 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7983536/