开发者

Changing method to static after calling it with the double colon in class in PHP

I have piece of code:

class example {
    public function say($x) {
        if ($x &开发者_StackOverflow中文版gt; 0) {
            echo $x;
            $this->say($x - 1);
        }
        else echo "0<br>\n";
    }
}

example::say(5);

Calling it I have:

 5
 Fatal error: Using $this when not in object context in (...).php on line 5

Why is this happening? What is happening to function 'say'? I see it's called once from outside a class, but why inside class PHP claims 'say' isn't accesible by '$this->'?


The error message is actually pretty clear: You cannot use $this, as you never created an instance of your example class. If you want to call your method statically, use this:

class example {
    public static function say($x) {
        if ($x > 0) {
           echo $x;
           self::say($x - 1); // static call
       }
       else {
           echo "0<br>\n";
       }
   }
}

example::say(5);

Or in a more object oriented way:

class example {
    public function say($x) {
        if ($x > 0) {
           echo $x;
           $this->say($x - 1);
       }
       else {
           echo "0<br>\n";
       }
   }
}

$x = new example();
$x->say(5);

You can call a non-static method statically, but you shouldn't (and this will only work if the method does not use $this). This is why PHP warns you if E_STRICT is enabled


Use self::say() or example::say(). $this should be used if you're in the object context (i.e. you have an example object instantiated with new).


You need to make use of the Scope Resolution Operator (::) to access the static methods within the class. As such, change line 5 to read...

example::say($x - 1);

(You could also use self:say to the same effect.)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜