2017-08-23 99 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($本 - > _配置)

在模板類初始化函數後返回空數組?

在此先感謝。

+1

爲什麼應該有價值? –

+1

您正在'init'內創建一個新的模板實例,它本身並沒有被初始化。你的類層次結構可能需要一些思考。 – iainn

+1

這根本不是繼承的工作原理。 – deceze

回答

1

我想你還沒有得到對象編程。在MyAppClass::init方法中,您將創建template類的新對象,該類可擴展您的MyAppClass類。我不知道你想要什麼,但我會告訴你,它的作品。

<?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方法重寫我的應用程序。謝謝你的樣品! –