2017-06-07 20 views
3
$protected_property_name = '_'.$name; 
    if(property_exists($this, $protected_property_name)){ 
     return $this->$protected_property_name; 
    } 

私はオブジェクト指向プログラミングのチュートリアルに従っていますが、インストラクターは私が持っていない新しいコード構造を思いついたなぜ彼がそれをしたのかについての明確な説明なしに、前に見た。 if(ステートメント)内に気付いた場合 $ this-> $ protected_property_nameステートメントは$ thisと$ protected_property_nameの2つの$記号を持っていますが、通常はドル記号を付けずに $ this-> protected_property_nameでなければなりませんprotected_property_name変数に追加します。 protected_property_name変数から$記号を削除しようとしたときにエラーが発生しました。完全なコードは次のようになります

class Addrress{ 

    protected $_postal_code; 

    function __get($name){ 
    if(!$this->_postal_code){ 
     $this->_postal_code = $this->_postal_code_guess(); 
    } 

    //Attempt to return protected property by name 

    $protected_property_name = '_'.$name; 
    if(property_exists($this, $protected_property_name)){ 
     return $this->$protected_property_name; 
    } 

    //Unable to access property; trigger error. 
    trigger_error('Undefined property via __get:() '. $name); 
    return NULL;   
} 
} 
+2

'ます$ this-> property_name'単にクラスのプロパティを指します。 '$ this-> $ property_name'は「可変プロパティ」です。件名のマニュアルは次のとおりです。http://php.net/manual/en/language.variables.variable.php –

+0

私はまだ混乱していますが、あなたは明確にしてください。私はマニュアルを読むが、それでも意味をなさない。 – Salim

答えて

2

> $のVARを:

class Example { 
    public $property_one = 1; 
    public $property_two = 2; 
} 

次のコードの違いを見ることができます:

$example = new Example(); 
echo $example->property_one; //echo 1 

$other_property = 'property_two'; 
echo $example->$other_property; // equal to $example->property_two and echo 2 

非OOP例:

$variable_one = 100; 
$variable_name = 'variable_one'; 
echo $$variable_name; // equal to echo $variable_one and echo 100 
+0

ありがとう、これは役に立ちました。基本的にother_property varの値はvar自体になります?? – Salim

+0

PHPでは、文字列から変数を二重 '$'記号で定義することができます。上記の例では、 '$$ other_property'は' $ property_two'変数と同じです。それはPHPの特別な機能です! –

4

は、私たちは私たちが$ x軸> myAttrのような公共の属性にアクセスすることができ、クラス

class Test { 
    public $myAttr = 1; 
} 
var $x = new Test(); 

を持っていると仮定しましょう。我々は

$var = 'myAttr'; 

のように、変数内の属性の名前を持っている場合我々は$ Xを持つ属性の値にアクセスすることができますどのような

- これは、例えばクラスです

関連する問題