使用外部函数直接在 php 构造函数中赋值

Assign value directly in php constructor with a external function

我可以在构造函数中为 属性 赋值,而不定义任何参数,例如使用外部函数吗?

例子

function my_external_function() {

     return 'Good Morning World';

}

class MyClass {

   protected $_my_property;

   public function __construct() {

        $this->_my_property = my_external_function() != '' ? my_external_function() : 'Good night World!';

   }

   public function getOtherMethod() {

       return $this->_my_property;

   }

}

$obj = new MyClass();
echo $obj->getOtherMethod();

是的,但你最好避免这种棘手的依赖关系。

可以做到这一点。您问题中的代码可以工作,但这种方法存在问题。

如果你这样写你的 class ,它将始终依赖于那个外部函数,但它甚至无法控制它是否存在,更不用说它是否会 return 构造函数可以使用的值。如果您移动、重命名或修改外部函数,它可能会以不可预知的方式改变您的 class 的行为。

我会推荐这样的东西,我认为它可以完成你想要完成的(不确定),而不会强迫你的 class 盲目地依赖外部函数。

class MyClass {

    protected $_my_property = 'Good night World!';  // set a default value here

    public function __construct($x = null) {  // give your constructor an optional argument
        if ($x) {                             // use the optional argument if it's provided
            $this->_my_property = $x;
        }
    }

    public function getOtherMethod() {
        return $this->_my_property;
    }
}

您仍然可以创建不带参数的 class 实例

$obj = new MyClass();

当您调用 $obj->getOtherMethod(); 时,您将获得默认值。

您仍然可以使用外部函数;只需让它将其值传递给对象的构造函数,而不是在构造函数中使用它。

$obj = new MyClass(my_external_function());