18/Aug
Fields and accessors
Starting with 3.0.5, PHPDS_dependant offers a little new trick: read-only fields.
The problem is, when in a class you have a field which should be readable but not writable, you are often lead to make it protected and write an accessor. The resulting code is, well, not really smart:
class service extends PHPDS_dependant
{
protected $quality = 'great';
public function quality()
{
return $this->quality;
}
}
From now on, just add the field, it will be read-only by default.
class service extends PHPDS_dependant
{
protected $quality = 'great';
}
$o = $this->factory('service');
print $o->quality; // prints "great"
$o->quality = "bad"; // ERROR!!!
Of course you can still have an accessor, and it will be called automatically:
class service extends PHPDS_dependant
{
protected $quality = 'great';
public function quality()
{
return $this->quality.'!!';
}
}
$o = $this->factory('service');
print $o->quality; // prints "great!!"
You can also have a read/write accessor:
class service extends PHPDS_dependant
{
protected $quality = 'great';
public function quality($value = null)
{
if (!is_null($value)) {
$this->quality = $value;
}
return $this->quality.'!!';
}
}
$o = $this->factory('service');
$o->quality = 'marvelous';
print $o->quality; // prints "marvelous!!"
In fact you can even have an accessor for a non-existent field...
A last note: as a side effect it prevent you from affecting a value to a non-declared field (unless the accessor catches it).
