::和 - >之间有什么区别? php的运营商?

时间:2011-06-07 09:27:54

标签: php oop class

  

可能重复:
  Reference - What does this symbol mean in PHP?
  In PHP, whats the difference between :: and -> ?

当你尝试访问类里面方法的属性时,和 - 和 - >之间的区别是什么?在某些地方是否有与php中面向对象编程相关的运算符的完整参考?

3 个答案:

答案 0 :(得分:6)

::用于静态属性和方法,例如

 MyClass::create();

->适用于从类中实例化对象的情况,例如

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

答案 1 :(得分:1)

使用::时,您可以静态访问Class方法而无需创建类的实例,如:

Class::staticMethod();

您可以在类的实例上使用->,例如:

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

答案 2 :(得分:0)

静态动态属性和方法之间存在差异。

观察这段代码以了解其中的区别:

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;
    }
}

文学为您提供便利: