Can I set up a default method argument with class property in PHP?

你离开我真会死。 提交于 2019-11-29 09:16:49

Yes, you have to do it this way. You cannot use a member value for the default argument value.

From the PHP manual on Function arguments: (emphasis mine)

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.

You absolutely can do this. Best of both worlds: initialize your default property AND your method's default argument with a class constant.

class Object {

    const DEFAULT_BLNOVERWRITE = TRUE;

    protected $blnOverwrite = self::DEFAULT_BLNOVERWRITE;

    public function place($path, $overwrite = self::DEFAULT_BLNOVERWRITE) {
        var_dump($overwrite);
    }
}

$Object = new Object();
$Object->place('/'); //bool(true)

You must do it that way, afaik, or use a class constant since php 5.3 but of course its fixed and cant be changed later so i would definitely go with your own solution:

class foo{
    const constant = 'bar';

    public function place($path, $overwrite = self::constant ) { 
        die('bla' . $overwrite);
    }
}

$bar = new foo();
$bar->place('baz');

you just can shorten it a little:

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

but thats nearly the same

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!