我正在使用
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开始:
原文链接:https://www.f2er.com/php/133183.htmlThe visibility of a property or method
can be defined by prefixing the
declaration with the keywordspublic
,
protected
orprivate
. Class members
declaredpublic
can be accessed
everywhere. Members declaredprotected
can be accessed only within the class
itself and by inherited and parent
classes. Members declared asprivate
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