Is there a way to access the base class through a Derived Class object directly in PHP

in php, is there a way to directly access any property of a base class directly through an object of a derived class type.

For instance,

class a { public $name="Something"; function show() { echo $this->name; } }; class b extends a { public $name="Something Else"; function show() { echo $this->name; } }; $obj = new b(); $obj->show(); 

it will print the string "Something Else", but what if I want to access the Base show class function,

it does not work, as is done in C ++

 obj.a::show(); 
+4
source share
1 answer

Since you are overriding $name in the child, the property will have the value of the child property. Then you cannot access the parent value. This would not make any sense, since the property is publicly available, which means that the property is visible to the child (and outside of it), and changes in it will change the most basic value. Thus, it is effectively the same property and value for this instance.

The only way to have two separate properties of the same name is to declare the base property private and the child property not private, and then call a method that has access to the base property, for example

 class Foo { private $name = 'foo'; public function show() { echo $this->name; } } class Bar extends Foo { public $name = 'bar'; public function show() { parent::show(); echo $this->name; } } (new Bar)->show(); // prints foobar 

Since your C ++ call uses the scope :: operator , you can look for class / static properties :

 class Foo { static public $name = 'foo'; public function show() { echo static::$name; // late static binding echo self::$name; // static binding } } class Bar extends Foo { static public $name = 'bar'; public function show() { parent::show(); // calling parent show() echo parent::$name; // calling parent $foo } } (new Bar)->show(); // prints barfoofoo 
+4
source

Source: https://habr.com/ru/post/1485327/


All Articles