Search code examples
phpclassobjectnon-static

How does the non-static method of a class is getting called statically from another different class' method without creating the object of former?


I'm using PHP 7.1.11

Consider below code :

<?php
  class A {
    function foo() {
      if (isset($this)) {
        echo '$this is defined (';
        echo get_class($this);
        echo ")\n";
      } else {
        echo "\$this is not defined.\n";
      }
    }
  }

  class B {
    function bar() {
      A::foo();
    }
  }

  $a = new A();
  $a->foo();

  A::foo();
  $b = new B();
  $b->bar();

  B::bar();
?>

Output of above code :

$this is defined (A)
$this is not defined.
$this is not defined.
$this is not defined.

Except the first line in the output the next three lines of output have been generated by calling the non-static method foo() which is present in class A statically(i.e. without creating an object of class A).

Someone please explain me how is this happening?

How does the non-static method from another class is getting called statically from the class/ object of class under consideration(i.e. class B here)?

Thank You.


Solution

  • Note: PHP is very loose with static vs. non-static methods

    But: Methods which are not static should NOT be called statically (even if PHP is tolerant). Why?

    If a method is not static, this usually means that it is depending on the state of an instance, because otherwise it could be made static.

    Sometimes a non-static method is not dependent on an instance and therefore a program still works, because this method could be static. But you never should do this.

    Furthermore - if you turn on error reporting, PHP will also tell you this:

    $this is defined (A)
    Deprecated: Non-static method A::foo() should not be called statically in [...][...] on line 25
    $this is not defined.
    Deprecated: Non-static method A::foo() should not be called statically in [...][...] on line 18
    $this is not defined.
    Deprecated: Non-static method B::bar() should not be called statically in [...][...] on line 29

    Deprecated: Non-static method A::foo() should not be called statically in [...][...] on line 18
    $this is not defined.

    The Deprecated also means: Just because PHP still allows this, it will most probably be removed in future PHP updates.