tags:

views:

167

answers:

5

Hi,

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

+10  A: 
MyClass::myFunction();  // static method call

$myclass->myFunction(); // instance method call
Arthur Frankel
So, does `myclass::myFunction();` compile, and if so, what does it mean?
Oskar
I just tried it and $myclass::myFunction() doesn't parse in php - which is good since by definition the static method should not be allowed to be executed from an instance.
Arthur Frankel
That makes sense, but you never know with PHP... :)
Oskar
+3  A: 

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

MyClass::myStaticFunction()

but not:

MyClass->myStaticFunction()
truppo
A: 
class MyClass {
  static function myStaticFunction(...){
  ...
  }

}

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

MyClass::myStaticFunction();
Carlos
+2  A: 

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();
JustinW
A: 

To be honest, I don't know...

JD-Daz