Page 1 of 1

Cannot access object after include

Posted: Sun Feb 07, 2010 10:04 am
by bare_nature
The topic title is rather vague so let me explain my problem with a code snippet:

Code: Select all

 
<?php
    require_once("initialize.php");
    include("header.php");
?>
 
body of the page
 
<?php
    include("footer.php");
?>
 
In initialize.php I create an instance of a class (let's name it "Foo") so it is readily available to me by requiring initialize.php. So far so good. By including header.php I include the typical header information that is consistent throughout the website.

However, in this header.php, I want to call the instance of Foo, I made, but it seems I have no access to that instance. How do I go about to have access to that instance of Foo in header.php?

I hope everything is clear. Advise and suggestions are welcome!

Bart

Re: Cannot access object after include

Posted: Sun Feb 07, 2010 10:43 am
by AbraCadaver
You need to show header.php and initialize.php. Maybe you are creating the object in a function or you are trying to access it in a function?

Re: Cannot access object after include

Posted: Sun Feb 07, 2010 11:09 am
by bare_nature
initialize.php:

Code: Select all

 
    require_once(LIB_PATH.DS."foo.php");
 
foo.php:

Code: Select all

 
    class Foo {
    
    private $random_variable = false;
    
    public function give_me_random_variable() {
        return $this->random_variable;
    }
}
 
$foo = new Foo();
 
header.php:

Code: Select all

 
    if (isset($foo->give_me_random_variable())) {
        // Do stuff
    }
 
The question is, how do I get access to $foo in header.php? It is not in the main flow of the page, because it is included.

Bart