What strategies are available to creating accessors and mutators for a PHP class’ private members? Is this suggestion good: http://cormacscode.wordpress.com/2009/01/22/read-only-object-variables-in-php-using-magic-methods/
<?php
class classWithReadOnlyVar
{
private $readOnlyVar;
public function __get($varName)
{
return $this->$varName;
}
public function __set($varName,$varValue)
{
}
}
What if some members needed a private, public, or protected property method?
First of all,
__get,__set, etc. are definedpublicand you cannot have them otherwise. Magic methods should be used wisely as it takes about three times as long to make a call to a magic method than simply calling a class method.Usually (normally, preferably), you will have your class members
privateorprotected(neverpublic) and have accessors and mutators to encapsulate them. Those accessors and mutator may be of any visibility, depending on what the user can do with the members. You may also have immutable classes by declaring only accessors for your members, which are initialized in the constructor only.So, your sample class should read
and should not use the magic methods.
There may be many reasons to avoid using magic methods at all :
protectedmagic methodClass members
Their visibility should be
privateorprotected, it all depends if you want them accessible by inheritence. They should never bepublicas this breaks the OO paradigm.Example of a protected member:
(without
$_namebeingprotected, this would not be possible, and no need to redefine the accessor)Accessors
They should be
protectedorpublic. Having aprivateaccessor makes no sense; a class should access it’s member directly. If the member needs processing, the class will know regardless when to call the accessor or not.Mutators
They should be
protectedorpublic. As for the accessors, it makes no sense to have aprivatemutator… unless a very rare case when processing needs to be done internally. If a class member has no accessor, it should not have a mutator. It also makes no sense to have a mean to set a value without being able to get the value back somehow.