简体   繁体   中英

What is the difference between -> and :: in PHP?

This thing has been bugging me for long and I can't find it anywhere!

What is the difference when using classes in php between :: and ->

Let me give an example.

Imagine a class named MyClass and in this class there is a function myFunction

What is the difference between using:

MyClass myclass = new MyClass
myclass::myFunction();

or

MyClass myclass = new MyClass
myclass->myFunction();

Thank you

MyClass::myFunction();  // static method call

$myclass->myFunction(); // instance method call

"::" is for calling static methods on the class. So, you can use:

MyClass::myStaticFunction()

but not:

MyClass->myStaticFunction()

as stated, "::" is for static method calls whereas "->" is for instance method calls

except for when using parent:: to access functions in a base class, where "parent::" can be used for both static and non-static parent methods

abstract class myParentClass
{
   public function foo()
   {
      echo "parent class";
   }
}

class myChildClass extends myParentClass
{
   public function bar()
   {
      echo "child class";
      parent::foo();
   }
}

$obj = new myChildClass();
$obj->bar();
class MyClass {
  static function myStaticFunction(...){
  ...
  }

}

//$myObject=new MyClass(); it isn't necessary. It's true??

MyClass::myStaticFunction();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM