Skip to content

Instantly share code, notes, and snippets.

@brzuchal
Created April 5, 2016 09:55
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 brzuchal/12ebda1efed59440a78ba43bff116728 to your computer and use it in GitHub Desktop.
Save brzuchal/12ebda1efed59440a78ba43bff116728 to your computer and use it in GitHub Desktop.
PHP Final Property redeclaration as non-final
<?php
class Article {
private final $comments = [];
public function addComment(Comment $comment) {
$this->comments[] = $comment;
}
public function clearComments() {
$this->comments = [];
}
}
class ExtendedArticle extends Article {
private $comments = [];
}
class Comment {}
$article = new Article();
$article->addComment(new Comment());
$article->addComment(new Comment());
$article->clearComments();
//Warning: Cannot change final property: Article::$comments which has already defined value in articles.php on line 8
var_dump($article);
//object(Article)#1 (1) {
// ["comments":"Article":private]=>
// array(2) {
// [0]=>
// object(Comment)#2 (0) {
// }
// [1]=>
// object(Comment)#3 (0) {
// }
// }
//}
$extendedArticle = new ExtendedArticle();
$extendedArticle->addComment(new Comment());
$extendedArticle->addComment(new Comment());
var_dump($extendedArticle);
//object(ExtendedArticle)#4 (2) {
// ["comments":"ExtendedArticle":private]=>
// array(0) {
// }
// ["comments":"Article":private]=>
// array(2) {
// [0]=>
// object(Comment)#5 (0) {
// }
// [1]=>
// object(Comment)#6 (0) {
// }
// }
//}
$extendedArticle->clearComments();
var_dump($extendedArticle);
//object(ExtendedArticle)#4 (2) {
// ["comments":"ExtendedArticle":private]=>
// array(0) {
// }
// ["comments":"Article":private]=>
// array(0) {
// }
//}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment