seedg
seedg

Reputation: 21935

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

Upvotes: 3

Views: 407

Answers (4)

Arthur Frankel
Arthur Frankel

Reputation: 4705

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

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

Upvotes: 11

JustinW
JustinW

Reputation: 271

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();

Upvotes: 2

Curlas
Curlas

Reputation: 899

class MyClass {
  static function myStaticFunction(...){
  ...
  }

}

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

MyClass::myStaticFunction();

Upvotes: 0

mthurlin
mthurlin

Reputation: 27285

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

MyClass::myStaticFunction()

but not:

MyClass->myStaticFunction()

Upvotes: 3

Related Questions