I’ve decided to have some fun, and implement .Net Properties in PHP.
My current design centers around something like:
$var;
method Var($value = null)
{
if($value == null) {
return $var;
}
else {
$var = $value;
}
}
Obviously this runs into a bit of an issue if someone is trying to set the property (and associated variable) to null, so I am thinking of creating a throwaway class that would never be used. Thoughts, comments?
Do not reinvent the wheel. PHP already provides the magic methods
__getand__setthat can be used to implement .NET-lookalike properties; there are examples on the documentation pages. PHP frameworks also use these hooks to redirect code execution to proper getter/setter methods (which really need to be distinct, for the reason you have discovered yourself) so that read-only properties can be achieved as well; an (admittedly complicated) example is this.Pro tip: if you do override
__getand__set, you will need to also override__issetand__unsetso that your class can continue to behave intuitively in the presence of constructs such asemptyandunset.