将变量从类实例传递到其扩展方法

时间:2014-03-04 17:13:01

标签: php class oop

我正在尝试将变量传递给扩展类中的方法,但它不起作用。

以下是示例代码:

class set2 extends set1
{
    function Body($variable) {
    }
}


$start2 = new set2();
$start2->Body('some text');

最后一行是我试图开始工作的部分。我不确定我是否应该使用构造函数来执行此操作,或者最好如何使其工作。

我明白了。我只是添加了一个公共变量,并传递了它的值:

class set2 extends set1
{
    public $variable = NULL;
    function Body() {
        echo $this->variable;
            }
}


$start2 = new set2();
$start2->variable = 'Some Text';

1 个答案:

答案 0 :(得分:1)

我认为你正在尝试做的三种不同方式:

class set1
{
    protected $headVariable;

    function Head() {
        echo $this->headVariable;
    }

    function Body($variable) {
        echo $variable;
    }

    function Foot() {
        echo static::$footVariable;
    }

}


class set2 extends set1
{
    protected static $footVariable;

    function Head($variable) {
        $this->headVariable = $variable;
        parent::Head();
    }

    function Body($variable) {
        parent::Body($variable);
    }

    function Foot($variable) {
        self::$footVariable = $variable;
        parent::Foot();
    }

}


$start2 = new set2();
$start2->Head('some text');
$start2->Body('some more text');
$start2->Foot('yet more text');
相关问题