PHP property as object

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

    Yes, it is. But this can be done during the class instantiation (in the constructor) or later, for example:

    • during instantiation:

      class A {
          public $a;
          public function __construct() {
              $this->$a = (object)array(
                  'property' => 'test',
              );
          }
      }
      
      $my_object = new A();
      echo $my_object->a->property; // should show 'test'
      
    • after instantiation:

      class B {
          public $b;
      }
      
      $my_object = new B();
      $my_object->b = (object)array(
          'property' => 'test',
      );
      echo $my_object->b->property; // should also show 'test'
      

    You can not assign object directly in class definition outside constructor or other methods, because you can do it only with scalars (eg. integers, strings etc.).

提交回复
热议问题