我读到了一个神奇的 getter 和 setter 函数,它取代了大量的标准 getter 和 setter。 (Link)
我更改了 Miles 的函数,因为我使用的是 AnnotationForms
并且不希望在 $_name
等变量中使用下划线。我更新了魔法功能,但是当尝试调用例如getName()
我得到:
Fatal error: Call to undefined method ... Entity::getName()
这是我的代码:
<?php
namespace Entity;
use Doctrine\ORM\Mapping as ORM;
use Zend\Form\Annotation as Form;
/**
* @ORM\Entity
* @ORM\Table(name="masterdata_entity")
* @Form\Name("entity")
* @Form\Attributes({ "class": "form-horizontal" })
* @Form\Hydrator("Zend\Stdlib\Hydrator\ObjectProperty")
*/
class Entity
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
* @Form\Exclude()
*/
protected $id;
/**
* @ORM\Column(type="string")
* @Form\Filter({"name":"StringTrim"})
* @Form\Validator({"name":"StringLength", "options":{"min":1, "max":50}})
* @Form\Attributes({"type":"text"})
* @Form\Options({"label":"Name"})
*/
protected $name;
public function __get($property) {
return (isset($this->{$property}) ? $this->{$property} : null);
}
public function __set($property, $value) {
if (isset($this->{$property})) {
$this->{$property} = $value;
}
}
public function __isset($property) {
return isset($this->{$property});
}
}
有什么想法以及如何解决它吗?
最佳答案
我想我的评论是正确的。检查DoctrineModule\Stdlib\Hydrator\DoctrineObject ,你会看到它基本上使用 \Zend\Stdlib\Hydrator\ClassMethods 。查看 extract()
函数,您可以看到所有 ClassMethods 都将在 line #60 处获取。
$methods = get_class_methods($object);
看看 line #63++你会看到只有默认的 getter getX, hasX, isX
才被视为有效:
if (!preg_match('/^(get|has|is)[A-Z]\w*/', $method)) {
continue;
}
这最终意味着,您将始终需要编写 setter 和 getter。即使文件大小可能会变大一点。它对于通常的 IDE 来说更好,而且即使文件大小也有性能提升。
关于php - Zend Framework 2 - 用于教义和注释表单的 Magic Getter 和 Setter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14054804/