Reputation: 27048
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?
Upvotes: 0
Views: 1630
Reputation: 18440
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();
Upvotes: 1
Reputation: 8519
I believe this tutorial leaves these properties as public so they can avoid implementing the magic methods __set()
and __get()
. Typically used in conjunction with mutators and accessors (setter and getter methods) to access protected and private properties in a class.
For Example:
/**
* 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;
}
The __get()
would be similar but reversed.
Upvotes: 0