【发布时间】: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