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

Aut*_*cus 1 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>';
}



//========================================================================================================================
}
?>
Run Code Online (Sandbox Code Playgroud)

它给了我这个错误

 Fatal error: Using $this when not in object context 
Run Code Online (Sandbox Code Playgroud)

Pek*_*ica 5

在静态函数中,您需要使用self:

print '<br> here it is:'.self::$x.'--<br>';
Run Code Online (Sandbox Code Playgroud)

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

也就是说,在静态上下文中,构造函数永远不会被调用,所以$x总是为空.我不确定public static function你是否真的想要这里.

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