次のような基本的なオブジェクトが与えられた場合 (AS3 での作業に基づく)、それ$friend
は解釈できます$this->friend
が、PHP パーサーは関数$friend
にローカライズされた初期化されていない変数としてしか認識しませんholler
。を使用せずにメンバー変数にアクセスする方法はあります$this->
か? 私の目標は、可能な限り無駄のない構文を発見することです。
class MyBuddy
{
private $friend = true;
public function holler()
{
if ( $friend ) // <- parser won't resolve $friend to a member variable
return 'Heeeeey Buuuuuday!';
else
return null;
}
}
更新:与えられた回答を検討した後、最も簡潔で理解しやすいアプローチは、関数の先頭にある関数レベル変数への参照によってインスタンス変数を渡すことです。これは、詳細なインスタンス変数を参照する関数にとって適切なソリューションです。
// Demonstrating a simple cache which abbreviates $this->thingCollection
// to $things for the function body
public function getThing( $id, $qty )
{
$things = &$this->thingCollection; // <-- pass by reference
if ( empty($things) )
$things = [];
if ( empty($things[$id]) )
$things[ $productId ] = [];
if ( empty($things[ $id ][ $qty ]) )
$things[ $id ][ $qty ] = get_thing_from_database( $id, $qty );
return $things[ $id ][ $qty ];
}