我可以在PHP中使用类属性设置默认方法参数吗? [英] Can I set up a default method argument with class property in PHP?
问题描述
我正在使用PHP 5.2.6.我想为方法中的参数提供默认值,但看来我有点太聪明了.
I'm using PHP 5.2.6. I want to have a default value for an argument in a method, but it seems I'm getting a bit too clever.
类属性blnOverwrite
是默认的,并且可以在该类的其他地方设置.我有一个方法想要再次设置它,但不覆盖现有值.尝试此操作时出现错误:
The class property blnOverwrite
is defaulted and settable elsewhere in the class. I have a method where I want to have it settable again, but not override the existing value. I get an error when I try this:
public function place( $path, $overwrite = $this->blnOverwrite ) { ... }
我必须做这样的事情吗?
Must I do something like this?
public function place( $path, $overwrite = NULL ) {
if ( ! is_null($overwrite) ) {
$this->blnOverwrite = $overwrite;
}
...
}
推荐答案
是的,您必须这样做.您不能将成员值用作默认参数值.
Yes, you have to do it this way. You cannot use a member value for the default argument value.
摘自PHP手册中有关函数参数的内容:(强调我的)
一个函数可以为标量参数定义C ++风格的默认值. […] PHP还允许使用数组和特殊类型NULL作为默认值. […] 默认值必须是一个常量表达式,而不是(例如)变量,类成员或函数调用. […]请注意,使用默认参数时,任何默认值都应为on任何非默认参数的右侧;否则,事情将无法按预期进行.
A function may define C++-style default values for scalar arguments. […] PHP also allows the use of arrays and the special type NULL as default values. […] The default value must be a constant expression, not (for example) a variable, a class member or a function call. […] Note that when using default arguments, any defaults should be on the right side of any non-default arguments; otherwise, things will not work as expected.
这篇关于我可以在PHP中使用类属性设置默认方法参数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!