class error Using $this when not in object context
I have the following class and its not accepting $this keyword in the method. can someone guid
<?php
class test {
function __construct($x, $y, $z){
$this->$x = $x;
$this->testFunction();
public static function testFunction(){
print '<br> here it开发者_StackOverflow社区 is:'.$this->$x.'--<br>';
}
//========================================================================================================================
}
?>
it gives me this error
Fatal error: Using $this when not in object context
In a static function, you need to use self
:
print '<br> here it is:'.self::$x.'--<br>';
$this
refers to an object instance, which does not exist in a static context.
That said, in a static context, the constructor will never have been called so $x
will always be empty. I'm not sure whether public static function
is really what you want here.
Edit: Additionally, as @netcoder points out, $x
needs to be declared a static member as well.
Your method is static, you can't use $this in static context. You have to use self, but it will trigger a Fatal error because $x is not declared as a static member.
This will work:
class test {
static protected $x = 'hello world';
static public function testFunction() {
echo self::$x;
}
}
Basically you are using the keyword $this outside the class. There are a lot of syntax errors here:
1 - a }
is missing probably in the first function.
2 - i think that not using one of the public
, protected
, private
keyword in a class's function declaration is a mistake.
3 - To call a variable you have to use the $this->var_name
syntax, while using a constant you should use the self::cons_name
.
精彩评论