PHP: how to access data members of a superclass in a subclass of the same name?

I've searched everywhere but couldn't find a solution for this. Below is my code where I want to access the $myvar

superclass in the subclass, but I don’t know how? when i use the keyword $this

it accesses a variable in the same class but not in the superclass. please, any help would be greatly appreciated.

<?php 


class First{
    protected $myvar = "First Class";
}


class Second extends First{

    public $myvar = "Second Class";

    function __construct(){
        echo $this -> myvar;// here I want to access the $myvar of super class
    }

} 

$obj = new Second();

 ?>

      

Note. I can implement the same functionality in java using the keyword super

.

+3


source to share


4 answers


You cannot overwrite when creating a subclass that inherits from the parent class. Therefore, you will have to change the name for it.



+1


source


The way you are trying to do this will not work, as Risier pointed out. Maybe static properties might be useful to you (depending on your needs)

<?php
class a {
    protected static $var = 'a';
}

class b extends a {
    protected static $var = 'b';

    public function __construct() {
        echo self::$var;
        echo parent::$var;

    }
}

$b = new b();

      

You can also restore a

to b

. You could use inheritance for methods and possibly other properties, being able to use the default in a

-constructor.



<?php
class a {
    protected  $var = 'a';
}

class b extends a {
    protected  $var = 'b';

    public function __construct() {
        echo $this->var;

        $a = new a();
        echo $a->var;

    }
}

$b = new b();

      

The main question I have to answer is why you want a class to inherit from another, but still want to be able to change / modify material in the parent. This is something counterproductive to the entire inheritance project.

+2


source


You can create a custom function that returns variables from the parent class. But keep in mind that the variables must be "private":

class First{
    private $myvar = "First Class";
    protected function get_variable($var_name)
    {
        return $this->{$var_name};
    }
}
class Second extends First{
    public $myvar = "Second Class";
    function __construct() {
        echo parent::get_variable('myvar');
    }

}
$obj = new Second();

      

+2


source


You will override the parent parameter: public $ myvar = "Second class"; Remove this line to use inheritance from the parent class or to change the parameter name of the child class.

+1


source







All Articles