[nycphp-talk] Getter/setter best practices
Paul A Houle
paul at devonianfarm.com
Tue Jan 12 12:15:09 EST 2010
Yitzchak Schaffer wrote:
> Hello all,
>
> What's BP for changing the values of protected properties within a
> class that also has public getter/setters? e.g. in Foo::doSomething()
> below:
>
I think you're better off making the "underlying" variable private,
and then always access it through the getters and setters... The
getters and setters aren't just there to make you type more characters,
they give you the option to add behaviors to the get and set operators.
There may be some special cases that you want to bypass these, but
generally you want to go through them.
Personally, I like the way that properties work in C#, and I've
implemented a PHP class that offers really sweet syntax for properties:
class bean {
public function __get($parameter) {
$getter_name="get_{$parameter}";
if(method_exists($this,$getter_name)) {
return $this->$getter_name();
}
if(method_exists($this,"_nails_get")) {
return $this->_nails_get($parameter);
}
throw new Exception("Attempted to get unsupported property
[$parameter]");
}
public function __set($parameter,$value) {
$setter_name="set_{$parameter}";
if(method_exists($this,$setter_name)) {
$this->$setter_name($value);
return;
}
if(method_exists($this,"_nails_set")) {
return $this->_nails_set($parameter,$value);
}
throw new Exception("Attempted to set unsupported property
[$parameter]");
}
}
This lets you write something like
class myclass extends bean {
function get_A() {...}
function set_B($value) {...}
}
then you can write
$instance=new myclass();
$a=$instance->A;
$instance->B=$b;
performance wise I wouldn't use this mechanism for something that's in
an inner loop, but it makes code with getters and setters "feel like
PHP" rather than "feel like Java." Note that this also has extension
points: _nails_set() and _nails_get() are new "magic methods" that can
catch properties that aren't defined in the standard way.
If you like, you could write your own version that supports named
exceptions and also supports
TheIrrationalCamelCaseConventionThatNeverDies rather than the
convention_that_doesnt_conflate_different_meanings_of_capitalization
(i.e. supports_PHP versus SupportsPHP or SupportsPhp?)
More information about the talk
mailing list