Cannot access object after include

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
bare_nature
Forum Newbie
Posts: 5
Joined: Sun Feb 07, 2010 8:25 am

Cannot access object after include

Post 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
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: Cannot access object after include

Post 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?
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
bare_nature
Forum Newbie
Posts: 5
Joined: Sun Feb 07, 2010 8:25 am

Re: Cannot access object after include

Post 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
Post Reply