PHP 自动取号,php – 自动获取/设置功能

我正在查看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

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

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

解决方法:

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,doctrine,symfony1

来源: https://codeday.me/bug/20190726/1541226.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值