2010-01-18 78 views
0

我有一个头的方法,显示在页面的顶部,它是一个类里面,我的头()方法中我在这里运行此代码启动一个新的探查物体......如何解决这个PHP错误?

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

后一堆其他文件进行编译,然后我有一个文件到页脚部分,在该文件中运行此代码,

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

但是我在现在的页脚文件收到此错误信息,

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

我怎样才能解决这个问题?在一个函数创建

+2

365的问题,恭喜! – 2010-01-18 05:27:13

+1

你几乎问这个_exact相同question_昨天:HTTP://计算器。com/questions/2080369/can-i-have-a-class-method-include-a-header-file-for-me-in-php 你不明白什么? – hobodave 2010-01-18 05:40:45

+2

请阅读http://php.net/manual/en/language.variables.scope.php两次。 – hobodave 2010-01-18 05:41:37

回答

6

如果您创建的头方法里面的$探查物体,它不会另一种方法是可用的,除非它是一个全球性的$探查器是一个全局变量,或者它是一个单例。

为了使全球性的,声明的标题方法之外$探查,然后头方法中,包括该行:

global $profiler;

包含在页脚法这条线也是如此。其余的代码可以保持原样。它应该工作。

3

变量是局部的功能。使用global keyword来声明一个全局变量。

0

我建议做$profiler主类的属性,并初始化它的构造方法中,因为它不是真正相关的报头。

假设这是主类

class Example { 
    private $profiler; 

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

    public function header() { 
     ... 
    } 
} 

所包含的水箱内,初始化这个对象和运行标题,这只是为了更加明确,使分别探查开始通话:

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

包含的页脚中:

$example->profiler->end(); 
0

可能的步骤:

所有的
  1. 首先确保您包括其中包含剖析类的文件。
  2. 如果你在一个函数里面使用profiler实例,你需要使用全局关键字:

    global $ profiler;

+0

你的意思是全球;) – 2010-01-18 06:14:21

+0

是的,这就是我的意思:更正:) – Sarfraz 2010-01-18 06:35:41

0

我认为,如果你删除会议()从你的头顶部您的问题将被固定...