PHP函数和变量继承

时间:2009-08-06 00:55:34

标签: php

有人可以帮助我理解PHP类中的变量/函数继承。

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

任何人都可以解释我如何获得函数来回显子类中的值。我应该使用接口吗?这是否与后期静态绑定有关(由于使用了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();

4 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

你可以这样做:

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

答案 2 :(得分:0)

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

echo static::$myVar;

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

答案 3 :(得分:0)

  

我想调用该函数   儿童班静态。

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

我建议尽量少使用“static”属性/方法,尤其是在尝试使用继承时,至少使用PHP< 5.3

由于PHP 5.3很新,它可能在几个月之前就不会在您的托管服务上提供......