Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php Inheritance

I am using PHP 5.3 stable release and sometimes I encounter very inconsistent behaviours. As far as I know in inheritance all attributes and methods(private, public and protected) in super class are passed child class.

class Foo
{
    private $_name = "foo";
}
class Bar extends Foo
{
    public function getName()
    {
        return $this->_name;
    }
}
$o = new Bar();
echo $o->getName();

//Notice: Undefined property: Bar::$_name in ...\test.php on line 11

But when Foo::$_name attribute is defined "public" it doesn't give error. PHP has own OO rules???

Thanks

Edit: Now all things are clear. Actually I was thinking in "inheritance" a new class is created and inherits all members independent from its ancestor. I didn't know "accessing" rules and inheritance rules are the same.

Edit According to your comments this snippet should give an error. But it is working.

class Foo
{
    private $bar = "baz";

    public function getBar()
    {
        return $this->bar;
    }
}

class Bar extends Foo
{}

$o = new Bar;
echo $o->getBar();      //baz
like image 866
jsonx Avatar asked Jan 11 '10 15:01

jsonx


1 Answers

From PHP Manual:

The visibility of a property or method can be defined by prefixing the declaration with the keywords public, protected or private. Class members declared public can be accessed everywhere. Members declared protected can be accessed only within the class itself and by inherited and parent classes. Members declared as private may only be accessed by the class that defines the member.

class A
{
    public $prop1;     // accessible from everywhere
    protected $prop2;  // accessible in this and child class
    private $prop3;    // accessible only in this class
}

And No, this is not different from other languages implementing the same keywords.

Regarding your second edit and code snippet:

No, this should not give an error because getBar() is inherited from Foo and Foo has visibility to $bar. If getBar() was defined or overloaded in Bar it would not work. See http://codepad.org/rlSWx7SQ

like image 177
Gordon Avatar answered Nov 15 '22 09:11

Gordon