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.