tags:

views:

105

answers:

5

I have a header method that shows in the top of a page, it is inside a class, inside my header() method I run this code here to start a new Profiler object...

//start new page timer object
$profiler = new Profiler;
$profiler->start();

After a bunch of other files are compiled, I then include a file into the footer section, in this file I run this code,

echo 'Page Generated in ' .$profiler->end(). ' of a second with ' .$_SESSION['querie_counter']. ' MySQL Queries';

However I am getting this error message in the footer file now,

Notice: Undefined variable: profiler in C:\webserver\htdocs\friendproject2\includes\footer.inc.php on line 21

Fatal error: Call to a member function end() on a non-object in C:\webserver\htdocs\friendproject2\includes\footer.inc.php on line 21

How can I fix this?

+3  A: 

Variables created in a function are local to that function. Use the global keyword to declare a global variable.

Ignacio Vazquez-Abrams
+5  A: 

If you created the $profiler object inside the header method, it will not be available in another method, unless it was a global $profiler was a global variable or it was a singleton.

To make it global, declare $profiler outside the header method and then inside the header method, include this line:

global $profiler;

Include this line in the the footer method as well. The rest of your code can stay the way it is. It should work.

aip.cd.aish
A: 

I'd suggest make the $profiler a property of the main class and initialize it inside the constructor method, since it's not really related to the header.

Assuming this is the main class

class Example {
    private $profiler;

    public function __construct() {
        $this->profiler = new Profiler;
    }

    public function header() {
        ...
    }
}

Inside the included header, initialize this object and run header, and just to make it more explicit, make the profiler start call separately:

$example = new Example();
$example->profiler->start();
$example->header();

Inside the included footer:

$example->profiler->end();
Anurag
A: 

Possible Steps:

  1. First of all make sure that you include the file which contains the profiler class.
  2. If you are using the profiler instance inside a function, you need to use the global keyword:

    global $profiler;

Sarfraz
You meant global ;)
James Hartig
yes that's what i meant: corrected :)
Sarfraz
A: 

Hi

I Think if you remove session() from the top of your header your problems will be fixed ...

Mike Redford