加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

Php继承

发布时间:2020-12-13 22:39:16 所属栏目:PHP教程 来源:网络整理
导读:我正在使用 PHP 5.3稳定版本,有时我会遇到非常不一致的行为.据我所知,在继承中,超类中的所有属性和方法(私有,公共和受保护)都是传递子类. class Foo{ private $_name = "foo";}class Bar extends Foo{ public function getName() { return $this-_name; }}$o
我正在使用 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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读