2011-05-09 56 views
2

使用此功能,訪問對象我想創建一個PHP導航:PHP:不能從包含的文件

function loadPage($pagename) { 
     if (!isset($pagename) || !file_exists($pagename . '.php')) { 
      include FRONTPAGE . '.php'; 
     } else { 
      include $pagename . '.php'; 
     } 
    } 

在我的索引我有以下幾點:

require 'includes/classes/core.php'; 
$core = new SH_Core(); 

我可以訪問所有來自$ core的其他類,如$ core-> database-> newConnection(); 而且我應該也可以在包含的文件中使用它。但我不能:

Notice: Undefined variable: core in C:\Users\Development\Development applications\localhost\htdocs\Shuze\frontpage.php on line 4 

Notice: Trying to get property of non-object in C:\Users\Development\Development applications\localhost\htdocs\Shuze\frontpage.php on line 4 

Fatal error: Call to a member function newConnection() on a non-object in C:\Users\Development\Development applications\localhost\htdocs\Shuze\frontpage.php on line 4 

回答

3

你需要給你的函數訪問$核心:

function loadPage($pageName) { 
    global $core; 
    //rest of code 
} 

你也可以把在你的包含文件,以及頂部。或者,您可以使用超全球性的$ GLOBALS ['core']。

+0

謝謝!這確實有效!愚蠢的我錯過了這一點..無法停止學習,哈哈。 – Fabian 2011-05-09 17:58:32

+0

謝謝你的分享。這是一個非常重要的規則。 – kta 2012-03-13 03:33:35

+0

-1:最糟糕的解決方案 – 2013-02-17 12:13:07