views:

89

answers:

2

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 won't allow you to override the instance variable, but it is possible in PHP.

Is it because since PHP is weak type language so it is possible?

A: 

You made the instance variable protected, this means extending classes can overwrite it. If you want to prevent that use private.

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

Galen
-1: this does not answer why one can do this in PHP, and cannot do it in Java.
rsenna
i read the question backwards
Galen
+7  A: 

No, it has nothing to do with weak typing.

I guess this was simply a design decision that the PHP developers took. It may be because it is more of a scripting language than Java. (In Java, you would need to have a "virtual" lookup table for fields to support this or, alternatively, automatically generated getters / setters).

aioobe
I'm out of votes so I can't bump up your answer, but this is the only one that's remotely close to answering the question of why in PHP, the superclass ivar is overridden whereas in Java et al, the superclass ivar is shadowed/hidden (and they're not quite the same).
BoltClock