2012-05-03 13 views
1

親クラスで値を設定するが、親クラスを拡張する子クラスでこれらの値にアクセスできないという奇妙な問題があります。子クラスの親プロパティ値へのアクセス

私は空の配列を印刷します。しかし、これを行うと、私はそれらの設定値にアクセスすることができます。

private function _load($app) 
{ 
    $app = new $app(); 
    $app->config = $this->config 
    $app->index; 

} 

class Child extends Parent 
{ 
    public $config; 
      .... 
} 

、私は親から設定データにアクセスすることができます。

+0

'app'クラスはどのようなものです:

は別の例を見ることができますか? –

+0

アプリクラスその子クラス – Eli

答えて

2

値が初期化される前に値にアクセスしています。まず、値を設定する必要があります。

例:メソッドは、子クラスのコンストラクタで値を設定する親クラスです。

class Child extends Parent 
{ 
    public function __construct() { 
     $this -> setConfig(); //call some parent method to set the config first 
    } 
    public function index() 
    { 
     print_r($this->config); // returns an empty array 
    } 
} 

更新:また、あなたは親のメソッドとプロパティあなたはどうなるだけで同じように仕事をしなければならない、OOP

class Parent { ..... } 
class child extends Parent { ..... } 
$p = new Parent(); // will contain all method and properties of parent class only 
$c = new Child(); // will contain all method and properties of child class and parent class 

の概念について混乱しているように見える。しかし通常のオブジェクト。

class Parent { 
    protected $config = "config"; 
} 
class Child extends Parent { 
    public function index() { 
      echo $this -> config; // THis will successfully echo "config" from the parent class 
    } 
}  

しかし、別の例

class Parent { 
    protected $config; 
} 
class Child extends Parent { 
    public function index() { 
      echo $this -> config; //It call upon the parent's $config, but so far there has been no attempt to set an values on it, so it will give empty output. 
    } 
} 
+0

hey starx、一週間前に初めて私を助けようとした後、私はコードを再作成してより合理化しました。今私は同じ問題で戻ってきた。私は、親クラスを拡張することはすべてのプロパティ値を継承すると思った。 – Eli

+0

@Eli、更新を見てください、それは助けてくれるでしょう:) – Starx

+0

私はそれらがちょうどタイプミスであると確信していますが、スコープの解像度は '$ config'の更新された例では間違っています。 –

1

親のプロパティが保護されているからです。 publicに設定すると、子クラスでアクセスできます。または、代わりにconfigを返す親クラスにメソッドを作成します。

public function getConfig() 
{ 
    return $this->config; 
} 
+0

+1はOPがパブリックアクセサーを使用することを正しく示唆しています。 –

+0

@MikePurcell、$ configは保護されていますが、publicアクセサーを作成する場合はそれを破壊します。 – Starx

+0

「破壊する」という意味がわかりませんが、あなたは正しいですが、子クラスは保護された$ configにアクセスする必要があります。 –

関連する問題