开发者

What is the difference between :: and -> operators in php? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicates:

Reference - What does this symbol mean in PHP?

In PHP, whats the difference between :: and -> ?

When you try to access property of method inside class whats the difference between :: and -> and is there full reference of operators related to object orient开发者_运维百科ed programming in php somewhere?


The :: is for static properties and methods, e.g.

 MyClass::create();

The -> is for when you have an object instantiated from the class, e.g.

$myObject = new MyClass;
$myObject->create();


When using :: you can access a Class method statically without creating an instance of the class, something like:

Class::staticMethod();

You would use -> on an instance of a Class, something like:

$class = new Class();
$class->classMethod();


It's the difference between static and dynamic properties and methods.

Observe this piece of code to appreciate the difference:

class MyClass {

    protected $myvar = 0;
    public static  $othervar = "test";
    public function start($value)
    {
         // because this is not static, we need an instance.
         // because we have an instance, we may access $this
         $this->myvar = $value;

         // although we may still access our static variable:
         echo self::$othervar;
    }


    static public function myOtherFunction ($myvar)
    {
        // its a static function, so we're not able to access dynamic properties and methods ($this is undefined)

        // but we may access static properties
        self::$overvar = $myvar;
    }
}

Literature for your conveinience:

  • http://php.net/manual/en/language.oop5.php
  • What are static and dynamic variables / methods in OOP?
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜