PHP: Can't access object from included file [duplicate]
Using this 开发者_Go百科function I want to create a PHP navigation:
function loadPage($pagename) {
if (!isset($pagename) || !file_exists($pagename . '.php')) {
include FRONTPAGE . '.php';
} else {
include $pagename . '.php';
}
}
In my index I have the following:
require 'includes/classes/core.php';
$core = new SH_Core();
I can access all the other classes from $core like $core->database->newConnection(); And I should be able to use that in the included file too. But I can't:
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
You need to give your function access to $core:
function loadPage( $pageName ) {
global $core;
//rest of code
}
You could also put at the top of your include file as well. Or, you can use the super-global $GLOBALS['core'].
精彩评论