- The number of copies of
$this->x
in memory depends:- If parent declares
private $x
, then the parent and child store separate copies of$this->x
. - If parent declares
protected $x
orpublic $x
, then parent and child access the same copy of$this->x
.
- If parent declares
- The child class is allowed to loosen visibility but not tighten it.
- Ex: If parent
Foo
hasprotected $x
, then childBar
may declarepublic $x
- Ex: If parent
Foo
haspublic $x
, then childBar
may not declareprotected $x
.
- Ex: If parent
- The child class changes the default value.
- Ex: If parent
Foo
hasprotected $x = 'foo'
, and if childBar
hasprotected $x
, then the default value of$x
will be different. (Foo
has defaultfoo
andBar has default
NULL`.)
- Ex: If parent
-
-
Save totten/8a1efedf512add98e3e808796b0eac63 to your computer and use it in GitHub Desktop.
What happens when a subclass overrides a property in PHP?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Foo { | |
protected $x = 'base'; // FIXME: Play with this line | |
public function goFoo() { | |
$this->x .= '-foo'; | |
return $this->x; | |
} | |
} | |
class Bar extends Foo { | |
//protected $x; // FIXME: Play with this line | |
public function goBar() { | |
$this->x .= '-bar'; | |
return $this->x; | |
} | |
} | |
printf("\n=== PHP Version: %s\n", PHP_VERSION); | |
$a = new Bar(); | |
print_r(array( | |
'goFoo' => $a->goFoo() | |
)); | |
print_r(array( | |
'goBar' => $a->goBar() | |
)); | |
print_r(array( | |
'x' => $a->x, | |
)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment