Reputation: 5761
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?
Upvotes: 0
Views: 46
Reputation: 437684
Do not reinvent the wheel. PHP already provides the magic methods __get
and __set
that 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 __get
and __set
, you will need to also override __isset
and __unset
so that your class can continue to behave intuitively in the presence of constructs such as empty
and unset
.
Upvotes: 2
Reputation: 175048
I don't understand what you're trying to achieve here. Do you want a getter?
public function getVar() {
return $this->var;
}
Do you want a setter?
public function setVar($newVar) {
$this->var = $newVar;
}
You can even make it public and have someone on the outside to set the var:
public $var;
...
$object->var = "New Var";
Upvotes: 0