为什么在子对象中调用parent的方法在PHP中有效?

时间:2014-04-02 08:31:35

标签: php inheritance parent-child static-methods overloading

我在PHP对象继承过程中发现了一些奇怪的东西。

我可以从子类调用NON静态父方法。

我找不到有关发生这种情况的可能性的任何信息。此外,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?

2 个答案:

答案 0 :(得分:1)

就是这样,父类的方法是从PHP中的子类调用的。如果覆盖方法,通常需要一种方法来包含父方法的功能。 PHP通过parent关键字提供此功能。请参阅http://www.php.net/manual/en/keyword.parent.php

答案 1 :(得分:0)

这是PHP的默认功能。这样,即使重写父方法,您仍然可以在子方法中添加其现有功能。 前 -

class vehicle {

function horn()
{
echo "poo poo";
}
}

class audi extends vehicle {
function horn()
{
parent::horn();
echo "pee pee";
}
}

$newvehicle =new audi();
$newvehicle->horn(); // this will print out "poo poo  pee pee"