Home > Software engineering >  classes interaction methods php
classes interaction methods php

Time:06-28

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';

    public 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();

edit: I have changed function __construct from protected to public according comments. It is indeed gives error, so if someone will review this issue now code is correct.

CodePudding user response:

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

If class B has no 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.

Note: As @Brian said, if you try to call new B('provided value') that will produce the following error:

Fatal error: Uncaught Error: Call to protected A::__construct() from global scope in ..

and to solve it just make the construct of class A public so class B.

  • Related