Maslosoft Framework Documentation
Flexible Application Foundation
Getters and setters
While public properties are convenient way to access object values, the drawback
is that there is not control of what happens when value is set. To overcome
this, MongoDocument
class can be used, which provides ready solution for
getters and setters.
To use this, name methods similarly to public class properties, prefixing it
with get
and set
, and with uppercase rest part of name. Please note, that
when using getters and setters, class property cannot be used internally.
To set value use getAttribute()
and setAttribute()
methods or define your own value holder.
Example of using getAttribute()
and setAttribute()
:
class MyModel extends MongoDocument
{
public $title = '';
public function setTitle($value)
{
// Extra processing
assert(!empty($value));
$this->setAttribute('title', $value);
}
public function getTitle()
{
return $this->getAttribute('title', $value);
}
}
Example of privatelly held value:
class MyModel extends MongoDocument
{
public $title = '';
private $_myTitle = '';
public function setTitle($value)
{
// Extra processing
assert(!empty($value));
$this->_myTitle = $value;
}
public function getTitle()
{
return $this->_myTitle;
}
}
Example of calling getters and setters implicitly:
$model = new MyModel;
$model->title = 'New title'; // Will call setter
echo $model->title; // Will call getter