3

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

4 Answers 4

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

$myclass->myFunction(); // instance method call
Sign up to request clarification or add additional context in comments.

3 Comments

So, does myclass::myFunction(); compile, and if so, what does it mean?
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.
That makes sense, but you never know with PHP... :)
3

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

MyClass::myStaticFunction()

but not:

MyClass->myStaticFunction()

Comments

2

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

Comments

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

}

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

MyClass::myStaticFunction();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.