PHP可以';不要在类方法中使用$this作为默认参数


PHP can't use $this as default argument in class method

为什么我不能这样做?

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;

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

您可以像下面这样尝试;

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'

在创建该类的对象时调用构造函数,并且您正试图在构造函数参数默认值中传递$this,因此$this对您的构造函数不可用。

$this只有在调用Constructorget之后才可用。

所以请试试这个

class Foo {
    private $val = array(
        'fruit' => 'apple',
        'color' => 'red'
    );
    function __construct( $arg = NULL ) {
        echo $arg===NULL?$this->val['color'] : $arg;
    }
}
$bar = Foo;