Skip to content

Instantly share code, notes, and snippets.

@totten
Last active September 20, 2016 03:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save totten/8a1efedf512add98e3e808796b0eac63 to your computer and use it in GitHub Desktop.
Save totten/8a1efedf512add98e3e808796b0eac63 to your computer and use it in GitHub Desktop.
What happens when a subclass overrides a property in PHP?
<?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,
));
  • 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 or public $x, then parent and child access the same copy of $this->x.
  • The child class is allowed to loosen visibility but not tighten it.
    • Ex: If parent Foo has protected $x, then child Bar may declare public $x
    • Ex: If parent Foo has public $x, then child Bar may not declare protected $x.
  • The child class changes the default value.
    • Ex: If parent Foo has protected $x = 'foo', and if child Bar has protected $x, then the default value of $x will be different. (Foo has default foo and Bar has default NULL`.)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment