开发者

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


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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜