0

Can someone explain how these line of code are working

class DemoStatic {
  function normalFunction() {
    echo "This is the normal function";
  }
  static function staticFunction() {
    echo "This is the static function";
  }
}
$classObj = new DemoStatic();

DemoStatic::normalFunction(); vs. $classObj->normalFunction();

and

DemoStatic::staticFunction(); vs. $classObj->staticFunction();

And the output is as below

This is the normal function

This is the normal function

This is the static function

This is the static function

Now I really don't understand that how come a normal function is accessible via :: Operator and static function is called using the class object.

Can someone please explain?

Community
  • 1
  • 1
Anjil Panchal
  • 834
  • 1
  • 8
  • 11
  • I got warning while running `DemoStatic::normalFunction();` `Strict standards: Non-static method DemoStatic::normalFunction() should not be called statically`. Do you have your warnings turned on? – Med Apr 30 '15 at 15:04
  • It is a possible duplicate of http://stackoverflow.com/questions/3754786/calling-non-static-method-with – mcserep Apr 30 '15 at 15:08
  • `::` is for calling a (static) method of a class. `->` is for calling a method on an instantiated object. If you don't know what an instantiated object is and how it's useful, you need to learn a bit more about the basics of OOP. A static class method is essentially just a function; only that it's part of a class and not a global function. – deceze Apr 30 '15 at 15:08
  • If your method has no reference to `$this` then you can call it statically even if it's not explicitly declared as such. Note that if you add `$this` to your staticFunction, you'll get a fatal. – Alex Howansky Apr 30 '15 at 15:09
  • @Med I have warnings turned on in my Xampp setup. – Anjil Panchal May 01 '15 at 03:28

0 Answers0