0

假设我有

class A {
    private $_property = 'string';

    public function method($property=$this->_property) {
        // ...
    }
}

它不允许我这样做。

我想这样做的原因是(可能是不好的做法,但仍然......):

  1. 我希望在此类中的每个方法中属性的默认值都是“字符串”,但我不希望public function method($property='string')因为如果我需要更改它,我必须在每个方法中都这样做

  2. 我想在实例化类并使用此方法时传递参数,所以最近我需要$class = new A(); $param = 'string2'; $class->method($param);

  3. 由于$_property是私有的,我无法更改其值

  4. 如果我做:

class A {
    private $_property = 'string';

    public function method($property) {
        $property = $this->_property;
    }
}

它不允许我从外部更改参数。我的意思是,无论第 2 点的代码如何,它始终是“字符串”。

无论如何从第一个引用的代码中实现这一点,而不公开属性,既不在方法内部分配参数的值?

4

3 回答 3

4

参数默认值需要是静态的,因为它们需要在编译时进行评估。如果您要创建类属性static,则可以使用它,但这可能不是您想要的。

最简单的方法可能是:

public function method($property = null) {
    $property = $property ?: $this->_property;
    ...
}

(使用 PHP 5.3 的速记?:运算符。)

于 2013-05-07T11:36:36.380 回答
2

我会在我的课堂上使用 const :

class A {
    const _property = 'string';

    public function method($property = self::_property) {
        echo $property;
    }
}
于 2013-05-07T11:40:25.673 回答
1

尝试做这样的事情:

Class A {

private $_property = 'string';

public function method($property=null) {
    if($property == null)
        $property = $this->_property;
}

它会模拟你需要的东西。当您不发送任何参数时,它将从您的班级中获取默认参数。

于 2013-05-07T11:36:54.127 回答