thejester thejester - 6 months ago 11
PHP Question

Assign value directly in php constructor with a external function

Can I assign to a property a value in the constructor, without define any parameter, using for instance an external function?

Example

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();

Answer

You can do this. The code in your question will work, but there is a problem with this approach.

If you write your class this way, it will always depend on that external function, but it will have no control over whether or not it even exists, let alone whether or not it will return a value the constructor can use. If you move, rename, or modify the external function, it could change the behavior of your class in unpredictable ways.

I would recommend something like this instead, which I think may accomplish what you're trying to accomplish (not sure) without forcing your class to blindly depend on an external function.

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;
    }
}

You can still create an instance of your class with no argument

$obj = new MyClass();

and when you call $obj->getOtherMethod(); you'll get the default value.

You can still use the external function; just let it pass its value into your object's constructor instead of using it within the constructor.

$obj = new MyClass(my_external_function());