开发者

Why can't bee() call bar() unless I prepend self::?

Why can't bee() call 开发者_运维百科bar() unless I prepend self:: ?

class X {
    function bar ()
    {
            echo "OK";
    }
    public static function bee ()
    {
            bar ();
    }
};
$x = new X ();
$x->bee ();


static functions do not have access to the $this pointer, but what you have written there is actually trying to call the global function bar(). A regular call to a method on $x would be something like:

class X
{
    ...
    static function Bee()
    {
        $this->Bar();
    }
}

but this is not good practice because then your static function depends on being called from an object and there is no point in having it be static.

http://en.wikipedia.org/wiki/Method_(computer_programming)#Static_methods

As mentioned above, a method may be declared as static, meaning that it acts at the class level rather than at the instance level. Therefore, a static method cannot refer to a specific instance of the class (i.e. it cannot refer to this, self, Me, etc.), unless such references are made through a parameter referencing an instance of the class, although in such cases they must be accessed through the parameter's identifier instead of this. Most importantly there is no need to make an object for accessing data .i.e. without creating an object we can access the data members of a static class.


you are insight of a static method. Inside of a static method you are not in the object context so you cannot call the method with $this, ...

self::bar() or X::bar (); does the job...

But be carefull. Stuff like that is not possible if you call it from a static method:

function bar ()
    {
            echo $this->test;
    }

I would not make the method static unless you need it!

BR,

TJ


Static methods get called via the scope resolution operator ::

X::bee();

Then inside bee() you call bar(), what is a regular function, not a method. Here you must call it the same way as mentioned above, but you can simplify the scope identifier to self

public static bee () {
  self::bar();
}

Just to remember: Every "function" inside a class is in real a method. If you omit the visibility identifier public is implicitly assumed, but it will remain a method and must be called like this.

I see bar() is not static. To call a regular method you need an instance of the object within the context you are going to call it. Here you can either make bee() non-static (then $this as reference to the current object is avaible), or you instanciate a new object within bee().

class X {
  public function bar () { /* .. */ }
  public function bee () { $this->bar(); }
}
$x = new X;
$x->bee();

or

class X {
  public function bar () { /* .. */ }
  public static function bee () {
    $x = new self();
    $x->bar();
  }
}
X:bee();

Whats better depends on what the methods should do (meaning: Whats the design of the class in whole):

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜