oop - Constructor can access parent private properties in PHP? -
when dealing inheritance in php found lack of knowledge, constructors , private properties.
let's take code example:
<?php class module { public $type; public function __construct($type) { $this->type = $type; } } class bmodule extends module { } class cmodule extends bmodule { } class { private $module; public function __construct(module $module) { echo 'set module '.__class__.' '.$module->type . php_eol; echo "<br>"; $this->module = $module; } public function getmodule() { echo "i (as " . __class__ . ") have module of type " . $this->module->type; homecoming $this->module->type; } } class b extends { } $m = new module('base-module'); $bm = new bmodule('bi-module'); echo "<br>--------a---------<br>"; $a = new a($m); echo "<br>a of type " . $a->getmodule(); echo "<br>--------b---------<br>"; $b = new b($bm); echo "<br>b of type " . $b->getmodule(); some questions:
shouldn't b construction phone call constructor in context of b? (and expect fail cause didn't inherited private property $module) or php phone call constructor, using/referencing methods , properties a? (including private ones) i can pass $b either module or bmodule object; because bmodule kid of module. php checking inheritance chain (checking parents) of passed object when verifying type hinting? so can pass constructor either object of type module or bmodule or cmodule?and example:
<?php class { private $a; protected $a_copy; public function __construct($a_value) { $this->a = $a_value; $this->a_copy = $this->a; } public function geta() { homecoming $this->a; } public function getcopya() { homecoming $this->a; } } class b extends { } $a = new a('value a'); $b = new b('value b'); echo "<br>-----a-----<br>"; echo $a->geta()."<br>"; echo $a->getcopya()."<br>"; echo "<br>-----b-----<br>"; echo $b->geta()." (i expect have no access \$a)<br>"; echo $b->getcopya()."<br>"; being property $a private, would expect not able access it or class b. little bit non-sense actual understanding.
this expected functionality, although b inherits of methods of a, they're not called in context of b, they're called in context of a. constructor called. means functions defined in can access a's properties when object extended. methods defined in cannot access properties of b however, appears understanding.
so shortly reply questions:
no, functions called in context of defined, not called. php check way downwards inheritance chain see if it's correct. kid of class can assumed have same functions. if b extends a, can utilize either b or parameter when it's type-hinted a, utilize b if it's type-hinted b php oop inheritance type-hinting
No comments:
Post a Comment