Why is it possible to override instance variables in PHP, but not in Java?

Consider the code below:

<?php class Base { protected $name = "Base"; public function getName() { return $this->name; } } class Foo extends Base { protected $name = "Foo"; } $f = new Foo(); echo $f->getName(); // output: Foo $b = new Base(); echo $b->getName(); // output: Base 

Since in other languages, such as Java, you cannot override the instance variable, but this is possible in PHP.

Is this because PHP is a weak type, so is that possible?

+6
java oop php instance-variables
source share
2 answers

No, this has nothing to do with the weak type .

I guess it was just a design decision that the PHP developers took. This may be because it is more of a scripting language than Java. (In Java, you will need to have a β€œvirtual” lookup table for fields to support this or, alternatively, automatically created getters / setters).

+12
source share

You have made instance protection secure, which means that class extensions can overwrite it. If you want to prohibit the use of private.

http://www.php.net/manual/en/language.oop5.visibility.php

-one
source share

All Articles