开发者

How to fix this PHP error?

开发者 https://www.devze.com 2022-12-17 10:55 出处:网络
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...

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\inclu开发者_Python百科des\footer.inc.php on line 21

How can I fix this?


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.


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


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();


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;


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号