|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
[2002-09-04 03:38 UTC] antonio dot afonso at link dot pt
[2002-09-05 16:12 UTC] jmcastagnetto@php.net
[2002-09-26 19:50 UTC] sniper@php.net
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Mon Nov 03 18:00:01 2025 UTC |
I am surprised that a subclass can redeclare parent class variables. It seems to me that this could hinder reusability, as a programmer must know all variables declared in the parent class (possibly coded by another programmer) to avoid mistakes. Consider the following code: ---code--- class Father { var $variable = "father"; function parentVar() {return $this->variable;} } class Child extends Father { var $variable = "child"; function childVar() {return $this->variable;} } $testChild = new Child(); echo "Expect child : ". $testChild->childVar() . "\n"; echo "Expect father : ". $testChild->parentVar() . "\n"; ---endcode--- In java or C++, Father::variable and Child::variable would be different variables; References to $this->variable would refer to Child::variable in Child and to Father::variable in Father. The redefinition would not break any functions written in Father. Member functions in Child could access Father::variable by specifying it. The PHP documentation hints that this was considered. Indeed, in the documentation for :: one can read "Sometimes it is useful to refer to functions and variables in base classes or to refer to functions in classes that have not yet any instances. The :: operator is being used for this." However, the actual behaviour is PHP is that the Child class overwrites the variable from the Father, as can be seen by running the script. The results are : Expect child : child Expect father : child Am I overseeing something ? Thanks for your attention, Alain Dresse