在子项中实例化对象;赋值给父类变量


Instantiating object in child; assign to parent class variable

正确的方法是什么:

// child
class B extends A {
   function __construct() {
        $this->object = new B; /// (or `new self` ?)
   }
}
// parent
class A {
   protected $object;
       private static function {
           $object = $this->object;
           // use the new instance of $object
       }
}

当我在代码中尝试此操作时,出现此错误:

Fatal error: Using $this when not in object context 我做错了什么? (这是指类A实例)

不能在静态方法中使用$this;$this只能在实例化对象中使用。

您必须将$object更改为静态并使用self::$object调用它

class B extends A {
   function __construct() {
        self::$object = new B;
   }
}
// parent
class A {
   static protected $object;
   private static function doSomething(){
       $object = self::$object;
       // use the new instance of $object
   }
}

不能使用 $this 在静态方法中引用对象,因此必须对其进行一些更改。使object成为受保护的静态成员。

class A {
  protected static $object;
   private static function() {
       $object = self::$object;
       // use the new instance of $object
   }
}