2017-08-23 7 views
-1
上記のコードで何が悪い
class MyAppClass { 

    protected $_config = array(); 

    protected $_template = ''; 

    public function init(){ 

     require_once('core_config.php'); // Inside is $_SC_config with an array of values 

     $this->_config = $_SC_config; 

     $this->_template = new template; 

     echo $this->_template->echo_base(); 

    } 

} 

class template extends MyAppClass{ 

    public function echo_base() { 

     var_dump($this->_config); // returns empty array 

    } 

} 

$myApp = new MyAppClass; 
$myApp->init(); 

ので拡張クラスは、親の変数の初期値のみを取得します

のvar_dump($この - > _設定)テンプレートクラスで

は、init関数の後に空の配列を返します。 ?

ありがとうございます。

+1

なぜ価値があるはずですか? –

+1

'init'の内部に新しいテンプレートインスタンスを作成していますが、それ自体は初期化されていません。あなたのクラス階層にはいくつかの考えが必要かもしれません。 – iainn

+1

これは継承の仕組みではありません。 – deceze

答えて

1

私はあなたがまだオブジェクトプログラミングをしていないと思います。 MyAppClass::initメソッドでは、MyAppClassクラスを拡張するtemplateクラスの新しいオブジェクトを作成します。あなたは何を欲しがっているのか分かりませんが、私はあなたの作品を見せてくれるでしょう。

<?php 
class MyAppClass { 

    protected $_config = array(); 

    protected $_template = ''; 

    protected function init(){ 

     //require_once('core_config.php'); // Inside is $_SC_config with an array of values 

     $this->_config = 'foo'; 

    } 

} 

class template extends MyAppClass{ 

    public function __construct(){ 
     $this->init(); 
    } 

    public function echo_base() { 

     var_dump($this->_config); // returns empty array 

    } 

} 

$myApp = new template; 
$myApp->echo_base(); 
+0

kmike、そうです、私はちょうどoopメソッドでアプリケーションを書き直し始めました。あなたのサンプルをありがとう! –

関連する問題