【问题标题】:PHP function and variable inheritancePHP函数和变量继承
【发布时间】:2009-08-06 00:55:34
【问题描述】:

谁能帮我理解 PHP 类中的变量/函数继承。

我的父类有一个所有子类都使用的函数。然而,每个子类都需要在这个函数中使用它自己的变量。我想静态调用子类中的函数。在下面的示例中,显示的是“世界”,而不是子类中的值。

谁能解释我如何让函数回显子类中的值。我应该使用接口吗?这是否与后期静态绑定有关(由于使用的是 5.3.0 之前的 PHP 版本,我无法使用该绑定)?

class myParent
{
    static $myVar = 'world';
    static function hello()
    {
        echo self::$myVar;  
    }
}

class myFirstChild extends myParent
{
    static $myVar = 'earth';
}

class mySecondChild extends myParent
{
    static $myVar = 'planet';
}

myFirstChild::hello();
mySecondChild::hello();

【问题讨论】:

  • 一个接口只定义了需要定义的功能,这样的东西是行不通的。后期静态绑定是你想要的,但正如你所说,你不能使用它。你到底需要这种行为做什么?可能有更好的方法来实现它。

标签: php


【解决方案1】:

是的,你不能那样做。 static $myVar 的声明不会以任何方式相互交互,正是因为它们是静态的,是的,如果你有 5.3.0,你可以绕过它,但你没有,所以你不能。

我的建议是只使用非静态变量和方法。

【讨论】:

  • 我决定在孩子的静态函数中创建一个“self”实例,然后将变量存储为非静态变量。
【解决方案2】:

你可以这样做:

class myParent
{
    var $myVar = "world";
    function hello()
    {
        echo $this->myVar."\n";      
    }
}

class myFirstChild extends myParent
{
    var $myVar = "earth";
}

class mySecondChild extends myParent
{
    var $myVar = "planet";
}

$first = new myFirstChild();
$first->hello();

$second = new mySecondChild();
$second->hello();

此代码打印

earth
planet

【讨论】:

    【解决方案3】:

    如果您使用的是 PHP 5.3,则此 echo 语句将起作用:

    echo static::$myVar;
    

    但由于您无法使用它,因此您唯一(不错的)选择是使hello() 函数不是静态的。

    【讨论】:

      【解决方案4】:

      我想在 静态子类。

      这真的会让你陷入麻烦,在一天结束之前让你发疯^^(它已经有,也许^^)

      我强烈建议使用尽可能少的“static”属性/方法,特别是如果您尝试使用继承,至少使用 PHP

      由于 PHP 5.3 是相当新的版本,它可能在几个月后无法在您的托管服务中使用...

      【讨论】:

        猜你喜欢
        • 2016-03-01
        • 2011-03-25
        • 1970-01-01
        • 1970-01-01
        • 2021-08-24
        • 2015-12-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多