【问题标题】:PHP can't use $this as default argument in class methodPHP 不能在类方法中使用 $this 作为默认参数
【发布时间】:2013-09-06 00:32:44
【问题描述】:

为什么我不能这样做?

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;

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

【问题讨论】:

  • 如果你需要那样做,那你就做错了。请改进您的示例。
  • 使用静态变量。当对象还没有被构造时,使用对象属性有什么意义?
  • $this在构造函数被调用时不存在,只有在对象被实际实例化后才存在
  • 问题不在于$this。您不能在 func/method 声明中使用 any 表达式。只有常量/文字值。
  • 不是传递$this->val,而是传递null。然后检查它是否是null。如果是,则传递私有变量。

标签: php class methods arguments this


【解决方案1】:

你可以像下面这样试试;

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'

【讨论】:

  • 或者更小一点的echo ($arg) ? $arg : $this->val['color'];
【解决方案2】:

当创建该类的对象并且您尝试在构造函数参数默认值中传递 $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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-25
    • 1970-01-01
    • 1970-01-01
    • 2021-02-05
    • 1970-01-01
    • 2013-04-27
    • 2011-03-06
    • 2019-05-20
    相关资源
    最近更新 更多