Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP property as object

Is it possible to set a property of a class as a object?

Like:

class User {

    public $x = "";
    public $y = new ErrorVO();
    public $w = new array();

}

1 Answers

In the constructor, yes.

class User
{
    public $x = "";
    public $y = null;
    public $w = array();

    public function __construct()
    {
        $this->y = new ErrorVO();
    }
}

Edit

KingCrunch made a good point: You should not hard-code your dependencies. You should inject them to your objects (Inversion of Control (IoC)).

class User
{
    public $x = "";
    public $y = null;
    public $w = array();

    public function __construct(ErrorVO $y)
    {
        $this->y = $y;
    }
}

new User(new ErrorVD());
like image 107
Philippe Gerber Avatar answered Apr 09 '26 05:04

Philippe Gerber



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!