PHP property as object

前端 未结 4 1897
感情败类
感情败类 2021-01-07 01:44

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         


        
4条回答
  •  囚心锁ツ
    2021-01-07 02:41

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

提交回复
热议问题