开发者

PHP: Can't access object from included file [duplicate]

This question already has answers here: Call to a member function on a non-object [duplicate] (8 answers) Closed 10 years ago.

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'].

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜