Search code examples
phpvariableszend-framework2protected

how to pass protected variables to the table model (or mapper) in Zend Framework 2?


I'm following the tutorial from zf2 website and at one point they create some properties:

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;
    }
}

they are public and if i make them protected then when i use them in my query i get an error saying that i can access them:

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

How can i keep them protected and access them in the Model Table (or Mapper)?

Any ideas?


Solution

  • You need to modify the code to use setters and getters, which is good practice anyway:-

    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
    }
    

    Then to access those properties:-

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