Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

classes interaction methods php

Lets say we have class B which extends class A. When creating new instance of class B and providing value into it that value is used in constructor of class A. Please check sample below.
I’m little bit confused about such behavior. If method "display" do not pass value into class A it should not get there, or am i missing something?

class A {
    protected $changeableString = 'initial value';

    protected function __construct($providedText)
    {
    $this->changeableString = $providedText;        
    }

    public function printString(){
        echo $this->changeableString;
    }
}
class B extends A {
    public function display(){
        echo $this->changeableString;
    }
}

$test = new B('provided value');
$test->display();

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

First of all the topic you are talking about is called Inheritance in Object-Oriented Programming (OOP).

If class B has no a construct (__construct) then PHP will call the construct of class A.

And about display function, think of it as an addition to everything in class A but will not be available in class A
So class B is like class A but has one more function called display.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading