0

我正在关注zf2 网站上的教程,并在某一时刻创建了一些属性:

namespace Album\Model;

class Album
{
    public $id;
    public $artist;
    public $title;

    public function exchangeArray($data)
    {
        $this->id     = (isset($data['id'])) ? $data['id'] : null;
        $this->artist = (isset($data['artist'])) ? $data['artist'] : null;
        $this->title  = (isset($data['title'])) ? $data['title'] : null;
    }
}

它们是public,如果我制作它们,protected那么当我在查询中使用它们时,我会收到一条错误消息,说我可以访问它们:

cannot access protected property Album\Model\Album::$artist

我如何保留它们protected并在模型表(或映射器)中访问它们?

有任何想法吗?

4

3 回答 3

1

您需要修改代码以使用 setter 和 getter,无论如何这是一个好习惯:-

namespace Album\Model;

class Album
{
    protected $id;
    protected $artist;
    protected $title;

    public function exchangeArray($data)
    {
        $this->id     = (isset($data['id'])) ? $data['id'] : null;
        $this->artist = (isset($data['artist'])) ? $data['artist'] : null;
        $this->title  = (isset($data['title'])) ? $data['title'] : null;
    }

    public function setId($id)
    {
        $this->id = $id;
    }

    public function getId()
    {
        return $this->id;
    }
    //You get the idea for the rest, I'm sure
}

然后访问这些属性:-

$album = new Album();
$album->setId(123);

$albumId = $album->getId();
于 2012-10-12T10:23:59.850 回答
0

添加吸气剂:

public function getId()
{
    return $this->Id;
}
于 2012-10-12T07:53:40.947 回答
0

我相信本教程将这些属性保留为公开,因此它们可以避免实现魔术方法__set()__get(). 通常与 mutators 和 accessors(setter 和 getter 方法)结合使用,以访问类中的受保护和私有属性。

例如:

/**
 * Map the setting of non-existing fields to a mutator when
 * possible, otherwise use the matching field
 * 
 *  $object->property = $value; will work the same as
 *  $object->setProperty($value);
 */
public function __set($name, $value)
    {

        $property = strtolower($name);

        if (!property_exists($this, $property)) {
            throw new \InvalidArgumentException("Setting the property '$property'
                    is not valid for this entity");
        }
        $mutator = 'set' . ucfirst(strtolower($name));

        if (method_exists($this, $mutator) && is_callable(array($this, $mutator))) {
            $this->$mutator($value);
        } else {
            $this->$property = $value;
        }


        return $this;
    }

__get()将是相似的,但相反。

于 2012-10-12T09:06:01.977 回答