0

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?

4

2 に答える 2

2

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.

于 2012-05-14T19:47:46.647 に答える
0

ここで何を達成しようとしているのかわかりません。ゲッターが欲しいですか?

public function getVar() {
    return $this->var;
}

セッターが欲しいですか?

public function setVar($newVar) {
    $this->var = $newVar;
}

それを公開して、外部に誰かを配置して変数を設定することもできます。

public $var;
...
$object->var = "New Var";
于 2012-05-14T19:50:04.290 に答える