【发布时间】:2014-04-02 08:31:34
【问题描述】:
我在PHP对象继承的过程中发现了一些奇怪的东西。
我可以从子类调用非静态父方法。
我找不到任何有关发生这种情况的可能性的信息。此外,PHP 解释器不会显示错误。
为什么有可能? 这是正常的 PHP 功能吗? 这是不好的做法吗?
这是一个可以用来测试它的代码。
<?php
class SomeParent {
// we will initialize this variable right here
private $greeting = 'Hello';
// we will initialize this in the constructor
private $bye ;
public function __construct()
{
$this->bye = 'Goodbye';
}
public function sayHi()
{
print $this->greeting;
}
public function sayBye()
{
print $this->bye;
}
public static function saySomething()
{
print 'How are you?';
}
}
class SomeChild extends SomeParent {
public function __construct()
{
parent::__construct();
}
/**
* Let's see what happens when we call a parent method
* from an overloaded method of its child
*/
public function sayHi()
{
parent::sayHi();
}
/**
* Let's call a parent method from an overloaded method of
* its child. But this time we will try to see if it will
* work for parent properties that were initialized in the
* parent's constructor
*/
public function sayBye()
{
parent::sayBye();
}
/**
* Let's see if calling static methods on the parent works
* from an overloaded static method of its child.
*/
public static function saySomething()
{
parent::saySomething();
}
}
$obj = new SomeChild();
$obj->sayHi(); // prints Hello
$obj->sayBye(); // prints Goodbye
SomeChild::saySomething(); // prints How are you?
【问题讨论】:
-
你有什么奇怪的?我不明白这是 PHP 的正常行为。
-
@Debflav 可能会造成混淆。
::- 用于访问静态数据的运算符,但使用parent::您可以调用非静态方法。 -
看看this问题
标签: php inheritance parent-child static-methods overloading