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
.
source to share
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.
source to share
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();
source to share