简体   繁体   English

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

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

Why cant I do this? 我为什么不能这样做?

class Foo {

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

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

        echo $arg

    }

}

$bar = Foo;

I have also tried this: 我也尝试过这个:

class Foo {

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

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

        echo $arg

    }

}

$bar = Foo;

I need to be able to provide default values for some of my method arguments from variables already defined within the class. 我需要能够从类中已经定义的变量中为某些方法参数提供默认值。

You can try it like below; 您可以像下面这样尝试;

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'

This will echo your default color in $val array defined in class or you can pass the initial $arg value so it will override the default; 这将在类中定义的$ val数组中回显您的默认颜色,或者您可以传递初始$ arg值,以便覆盖默认值;

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

Constructor is called when object of that class created and you are trying to pass $this in constructor parameter default value so at that $this is not available to your constructor. 当创建该类的对象并且您试图在构造函数参数默认值中传递$this ,构造函数将被调用,因此$this对于构造函数不可用。

$this is available only after Constructorget called. $this仅在调用Constructorget之后可用。

so please try this 所以请尝试这个

class Foo {

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

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

    }

}

$bar = Foo;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM