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.
In the same way that the child class can have its own properties and methods, it can override the properties and methods of the parent class. When we override the class's properties and methods, we rewrite a method or property that exists in the parent again in the child, but assign to it a different value or code.
Inheritance in OOP = When a class derives from another class. The child class will inherit all the public and protected properties and methods from the parent class. In addition, it can have its own properties and methods. An inherited class is defined by using the extends keyword.
PHP doesn't support multiple inheritance but by using Interfaces in PHP or using Traits in PHP instead of classes, we can implement it. Traits (Using Class along with Traits): The trait is a type of class which enables multiple inheritance.
PHP programming language doesn't even support the multiple inheritance/inheritances. PHP supports multiple inheritances only by using interfaces or Traits in PHP instead of classes so that we can implement it. Traits are a type of class that enables multiple case classes, objects, classes, and traits.
You're only instantiating class B
. Ignore A
for the moment, and pretend that methodA()
is part of class B
.
When class B
extends A
, it gets all of A
's functions. $this->B
isn't evaluated until the code is running, not prior. Therefore no error occurs, and won't occur as $this->B
exists in class B
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With