class error当不在对象上下文中时使用$ this

时间:2010-11-10 17:19:54

标签: php

我有以下类,并且它不接受方法中的$ this关键字。 可以有人指导

<?php
class test {

    function __construct($x, $y, $z){

        $this->$x = $x;


        $this->testFunction();





public static function testFunction(){



    print '<br> here it is:'.$this->$x.'--<br>';
}



//========================================================================================================================
}
?>

它给了我这个错误

 Fatal error: Using $this when not in object context 

3 个答案:

答案 0 :(得分:5)

在静态功能中,您需要使用self

print '<br> here it is:'.self::$x.'--<br>';

$this指的是一个对象实例,它在静态上下文中不存在。

也就是说,在静态上下文中,构造函数永远不会被调用,因此$x将始终为空。我不确定public static function是否真的是你想要的。

编辑此外,正如@netcoder指出的那样,$x也需要被声明为静态成员。

答案 1 :(得分:2)

您的方法是静态的,您不能在静态上下文中使用$ this。您必须使用 self ,但它会触发致命错误,因为$ x未声明为静态成员。

这将有效:

class test {

   static protected $x = 'hello world';

   static public function testFunction() {
      echo self::$x;
   }

}

答案 2 :(得分:0)

基本上你在课外使用关键字$ this。 这里有很多语法错误:

1 - 第一个函数中可能缺少}。 2 - 我认为在类的函数声明中不使用publicprotectedprivate关键字之一是错误的。 3 - 要调用变量,您必须使用$this->var_name语法,而使用常量则应使用self::cons_name

相关问题