Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP inheritance, parent functions using child variables

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.

like image 512
Bojan Dević Avatar asked Mar 15 '12 19:03

Bojan Dević


People also ask

Can child classes override properties of their parents?

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.

How the child class can access the properties of parent class explain with PHP example?

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.

Which inheritance is not supported in PHP?

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.

Why Multiple inheritance is not used in PHP?

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.


1 Answers

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.

like image 200
Brad Avatar answered Sep 28 '22 09:09

Brad