PHP:无法从包含的文件访问对象

发布于 2024-11-06 04:20:17 字数 933 浏览 0 评论 0原文

使用此函数,我想创建一个 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

Using this 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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

残花月 2024-11-13 04:20:17

您需要让您的函数访问 $core:

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

您也可以将其放在包含文件的顶部。或者,您可以使用超级全局 $GLOBALS['core']。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文