PHP property as object

前端 未结 4 1922
感情败类
感情败类 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:39

    Just my preferred solution, even if the others already explain everything: Injection

    class A {
      public $a;
      public function __construct (ErrorVO $a) {
        $this->a = $a;
      }
    }
    

    This keeps the class testable and allows to replace the wanted ErrorVO-implementation very easy. Of course you can combine both solutions into one

    class A {
      public $a;
      public function __construct (ErrorVO $a = null) {
        $this->a = is_null($a) ? new ErrorVO : $a;
      }
    }
    

    Minor Update: In the meantime you can write the second example like this

    class A {
      public $a;
      public function __construct (ErrorVO $a = null) {
        $this->a = $a ?: new ErrorVO;
      }
    }
    

    It's slightly more compact and imo it makes the intention more clear. Compare the ?:-operator with MySQLs COALESCE

提交回复
热议问题