gpt4 book ai didi

php - 我可以在 PHP 中使用类属性设置默认方法参数吗?

转载 作者:IT王子 更新时间:2023-10-28 23:52:28 24 4
gpt4 key购买 nike

我使用的是 PHP 5.2.6。我想为方法中的参数设置默认值,但似乎我有点太聪明了。

类属性 blnOverwrite 是默认的,可以在类的其他地方设置。我有一个方法,我想再次设置它,但不覆盖现有值。尝试此操作时出现错误:

public function place( $path, $overwrite = $this->blnOverwrite ) { ... }

我必须这样做吗?

public function place( $path, $overwrite = NULL ) { 
if ( ! is_null($overwrite) ) {
$this->blnOverwrite = $overwrite;
}
...
}

最佳答案

是的,你必须这样做。您不能将成员值用作默认参数值。

From the PHP manual on Function arguments: (强调我的)

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 - 我可以在 PHP 中使用类属性设置默认方法参数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3823018/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com