自动Getter/Setter功能

Shr*_*der 3 php doctrine symfony1

我正在查看Doctrine 2和Symfony文档来创建模型类.有几个代码片段,其中在类中使用了getProperty和setProperty,当值直接分配给属性时,它们会以某种方式自动使用.这与典型的get/set魔术方法不同,我遇到的示例代码没有实现任何自定义魔术方法,所以我相信这是由Doctrine在某处处理的.

从我读过的内容来看,Doctrine实现了访问器和mutator.也许我在下载Pear时错过了一个软件包,或者我的脚本中没有包含一些内容.

例如:

class User {

    public $name;
    public function getName()
    {
        // Do stuff
    }
}

$user = new User();
$foo = $user->name; // getName is called
Run Code Online (Sandbox Code Playgroud)

注意:我正在寻找一个特定于Doctrine的解决方案.我知道这可以用PHP来完成,但我想使用Doctrine的本机函数.

编辑:更新以阐明这与典型的获取/设置魔术方法的区别,并注意.

gus*_*tkg 6

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"
Run Code Online (Sandbox Code Playgroud)

如果有方法,getSomething或者setSomething在直接访问属性时将调用它.

正如我在本文档页面中所读到的那样,正是上面的代码完成了Doctrine所做的工作.但它称之为方法_set('fieldName', 'value').