Php继承

前端之家收集整理的这篇文章主要介绍了Php继承前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用 PHP 5.3稳定版本,有时我会遇到非常不一致的行为.据我所知,在继承中,超类中的所有属性方法(私有,公共和受保护)都是传递子类.
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

但是当Foo :: $_ name属性定义为“public”时,它不会给出错误. PHP有自己的OO规则???

谢谢

编辑:现在一切都很清楚了.
实际上我在思考“继承”时创建了一个新类,并且继承了独立于其祖先的所有成员.我不知道“访问”规则和继承规则是一样的.

编辑
根据你的评论,这个片段应该给出错误.但它正在发挥作用.

class Foo
{
    private $bar = "baz";

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

class Bar extends Foo
{}

$o = new Bar;
echo $o->getBar();      //baz
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
}

不,这与实施相同关键字的其他语言没有什么不同.

关于您的第二个编辑和代码段:

不,这不应该给出错误,因为getBar()是从Foo继承而Foo可以看到$bar.如果在Bar中定义或重载了getBar(),它将无法工作.见http://codepad.org/rlSWx7SQ

原文链接:https://www.f2er.com/php/133183.html

猜你在找的PHP相关文章