PHP不能在类方法中使用$ this作为默认参数

时间:2013-09-02 21:31:07

标签: php class methods arguments this

为什么我不能这样做?

class Foo {

    private $val = array(
        'fruit' => 'apple',
        'color' => 'red'
    );

    function __construct( $arg = $this->val['color'] ) {

        echo $arg

    }

}

$bar = Foo;

我也试过这个:

class Foo {

    private static $val = array(
        'fruit' => 'apple',
        'color' => 'red'
    );

    function __construct( $arg = self::val['color'] ) {

        echo $arg

    }

}

$bar = Foo;

我需要能够从已经在类中定义的变量为我的一些方法参数提供默认值。

2 个答案:

答案 0 :(得分:0)

您可以尝试以下内容;

class Foo {

private $val = array(
'fruit' => 'apple',
'color' => 'red'
);

function __construct($arg=null) {

echo ($arg==null) ? $this->val['color'] : $arg;

}

}

$bar = new Foo; // Output 'red'

这将在类中定义的$ val数组中回显您的默认颜色,或者您可以传递初始$ arg值,以便它将覆盖默认值;

$bar = new Foo('Yellow'); // Output 'Yellow'

答案 1 :(得分:0)

当创建该类的对象并且您尝试在构造函数参数默认值中传递$this时,将调用构造函数,因此构造函数无法使用此$。

只有在调用Constructorget后才能使用

$this

所以请试试这个

class Foo {

    private $val = array(
        'fruit' => 'apple',
        'color' => 'red'
    );

    function __construct( $arg = NULL ) {
        echo $arg===NULL?$this->val['color'] : $arg;

    }

}

$bar = Foo;