インスタンス変数がPHPクラスで参照されている場合、メソッドを実行しますか?
-
10-10-2019 - |
質問
変数がメソッドを保持するためのJavaScriptの能力と同様に、単にその値を返すのではなく、PHPクラスの変数を参照するときに関数を実行することは可能ですか?
class LazyClassTest()
{
protected $_lazyInitializedVar;
public function __construct()
{
/* // How can this call and return runWhenReferrenced() when
// someone refers to it outside of the class:
$class = new LazyClass();
$class->lazy;
// Such that $class->lazy calls $this->runWhenReferrenced each
// time it is referred to via $class->lazy?
*/
$this->lazy = $this->runWhenReferrenced();
}
protected function runWhenReferrenced()
{
if (!$this->_lazyInitializedVar) {
$this->_lazyInitializedVar = 'someValue';
}
return $this->_lazyInitializedVar
}
}
解決
これはphp5.3のように聞こえます:lambda /閉鎖 /匿名関数
http://php.net/manual/en/functions.anonymous.php:
<?php
$greet = function($name) {
printf("Hello %s\r\n", $name);
};
$greet('World');
$greet('PHP');
?>
他のヒント
php5sマジックメソッド __get($key)
と __set($key, $value)
あなたが必要とするものかもしれません。それらの詳細については、で入手できます PHPマニュアル.
あなたはおそらく間違った方向に向かっているでしょう。通常、ゲッターを定義したいです getLazyVar()
. 。人々が常にプロパティを保護および定義されたゲッター /セッターを作成する理由があります。したがって、彼らは値を事前に処理またはポストプロセスすることができます。
所属していません StackOverflow