【问题标题】:Why calling parent’s method in child object works in PHP?为什么在子对象中调用父对象的方法在 PHP 中有效?
【发布时间】: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


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    这是 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"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-09
      • 1970-01-01
      • 1970-01-01
      • 2020-07-03
      相关资源
      最近更新 更多