2

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
tereško
  • 58,060
  • 25
  • 98
  • 150
Fabian
  • 47
  • 7

1 Answers1

3

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

Kevin Nelson
  • 7,613
  • 4
  • 31
  • 42
  • Thanks! This worked indeed! Stupid I missed that out.. Can't stop learning, haha. – Fabian May 09 '11 at 17:58
  • Thank you for sharing.This is a very important rule. – kta Mar 13 '12 at 03:33
  • -1: worst possible solutions – tereško Feb 17 '13 at 12:13
  • @tereško, why are you downgrading me for answering the guys question? If he wants to use globals, that's the way you do it. Yes, dependency injection, etc., would be better, but he wasn't asking a question about architecture. So, if you're going to -1 me, please elaborate on how I was failing to answer the question or provide your "better" solution on how to access globals. – Kevin Nelson Feb 22 '13 at 16:07