While reviewing some PHP code I’ve discovered a strange thing. Here is the simple example illustration of it:
File A.php:
<?php
class A{
public function methodA(){
echo $this->B;
}
}
?>
File B.php:
<?php
class B extends A{
public $B = "It's working!";
}
?>
File test.php:
<?php
require_once("A.php");
require_once("B.php");
$b = new B();
$b->methodA();
?>
Running test.php prints out “It’s working!”, but question is why is it working? 🙂 Is this a feature or a bug? Method methodA in class A can also call methods that are in class B which should not work in OOP.
You’re only instantiating class
B. IgnoreAfor the moment, and pretend thatmethodA()is part of classB.When class
BextendsA, it gets all ofA‘s functions.$this->Bisn’t evaluated until the code is running, not prior. Therefore no error occurs, and won’t occur as$this->Bexists in classB.