gpt4 book ai didi

继承

转载 作者:可可西里 更新时间:2023-11-01 13:09:03 27 4
gpt4 key购买 nike

我使用的是 PHP 5.3 稳定版,有时会遇到非常不一致的行为。据我所知,在继承中,父类(super class)中的所有属性和方法(私有(private)、公共(public)和 protected )都传递给子类。

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

关于继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2042649/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com