2013-02-19 64 views
0

這一直在推動我堅果(喝淫穢的咖啡量和通宵工作並沒有幫助)我想從我在應用程序內的任何地方訪問一個類。我在我的索引頁實例化類(它會自動加載我的lib/classes)但是我似乎無法獲得對它的全局訪問。這是我的索引頁:Php訪問全球分類

function __autoload($class) 
{ 
    require LIBS . $class .'.php'; 
} 

$Core = new Core($server, $user, $pass, $db); 

這種自動載入我的庫/類完美,然後我實例化我的核心(這是我的庫/ core.php文件中加載自動)

然後在我的核心就是我創建了通常的數據庫連接,獲取並檢查URL以及實例化幾個類(哪些是自動加載的)的地方,我創建了__construct,這是我想要實例化Template類的地方。我希望在我的任何控制器和模型中都有全局訪問權限。

class Core { 

    function __construct(DATABASE VARIABLES IN HERE) 
    { 
     $this->Template = new Template(); 
    } 

} 

好了,所以我想我可以做訪問模板對象我父模型和父控制器內的下列:

class Controller 
{ 

    public $Core; 

    function __construct() 
    { 
     global $Core; 
     $this->Core = &$Core; 
    } 
} 

控制器是父,延伸着我的所有控制器,因此我認爲我可以只寫$this->Core->Template->get_data();來訪問一個模板方法?這似乎會引發錯誤。

我確定它一定是我忽略的一些簡單的東西,如果有人能給我一隻很棒的手。這個問題讓我瘋狂。

而且我__construct內我的孩子控制器內一個側面說明我構建父parent::_construct();

的錯誤似乎是Notice: Trying to get property of non-objectFatal error: Call to a member function get_data() on a non-object

+0

爲什麼不把'$ Core'作爲參數傳遞給構造函數? – 2013-02-19 19:47:19

+0

相關閱讀:http://stackoverflow.com/questions/11923272/use-global-variables-in-a-class/11923384#11923384 – PeeHaa 2013-02-19 19:54:33

回答

0
class Controller 
{ 

    public $Core; 

    function __construct(Core $core) 
    { 
     $this->Core = $core; 
    } 
} 

class ControllerChild extends Controller { 
    function __construct(Core $core, $someOtherStuff){ 
     parent::__construct($core) ; 
     //And your $this->Core will be inherited, because it has public access 
    } 
} 
  • 記:你沒有使用對象時使用&跡象。對象通過引用自動傳遞。
+0

嗨@Jari我試過了,發生以下錯誤Catchable致命錯誤:參數1通過到Controller :: __ construct()必須是Core的一個實例,沒有給出, – HireLee 2013-02-19 19:59:17

+0

@LeeMarshall您必須傳遞一個Core實例。像'新的ContollerChild(新的核心());' – vikingmaster 2013-02-19 20:03:30

0

您可以製作Core a singleton並實現一個靜態函數來接收指向該對象的指針。

define ('USER', 'username'); 
define ('PASS', 'password'); 
define ('DSN', 'dsn'); 

class Core { 

    private static $hInstance; 

    public static function getInstance() { 
    if (!(self::$hInstance instanceof Core)) { 
     self::$hInstance = new Core(USER, PASS, DSN); 
    } 

    return self::$hInstance; 
    } 

    public function __construct($user, $pass, $dsn) { 
    echo 'constructed'; 
    } 
} 

那麼你的控制器中,你可以使用:

$core = Core::getInstance(); 

應該輸出constructed

編輯

更新,演示如何通過靜態函數w /輸出構建。

+0

感謝您的評論,我把代碼放在我的Core類中,並把$ core = Core :: getInstance();併發生以下錯誤致命錯誤:未知的異常'異常'消息'Core尚未構建' – HireLee 2013-02-19 19:57:33

+0

是的,您需要先構造它。看到我的更新 – Martin 2013-02-19 19:59:18

+0

我得到了無法重新聲明類索引的致命錯誤,以及Core :: construct() – HireLee 2013-02-19 20:13:57