jsonx
jsonx

Reputation: 1089

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

Upvotes: 6

Views: 2741

Answers (3)

Gordon
Gordon

Reputation: 317197

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

Upvotes: 12

user248146
user248146

Reputation:

Private methods and variables cannot be accessed by child classes or externally - only by the class itself. Use Protected if you want the variable accessible by the child but inaccessible to outside classes.

Upvotes: 1

Decent Dabbler
Decent Dabbler

Reputation: 22793

Your assumptions aren't correct. Protected and public members are 'passed on'. Private members aren't. To my knowledge this is typical for many OOP languages.

Upvotes: 3

Related Questions