簡體   English   中英

為什么在子對象中調用父對象的方法在PHP中有效?

[英]Why calling parent’s method in child object works in PHP?

我在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?

這樣,可以從PHP的子類中調用父類的方法。 如果覆蓋方法,則通常需要一種方法來包含父方法的功能。 PHP通過parent關鍵字提供此功能。 參見http://www.php.net/manual/zh/keyword.parent.php

這是PHP的默認功能,通過這種方式,即使在重寫父方法之后,您仍然可以在子方法中添加其現有功能。 EX-

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"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM