代码之家  ›  专栏  ›  技术社区  ›  TheLettuceMaster

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

  •  0
  • TheLettuceMaster  · 技术社区  · 12 年前

    这样做的正确方法是什么:

    // 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 实例)

    2 回复  |  直到 12 年前
        1
  •  3
  •   Ibu    12 年前

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

    您必须将$object更改为static,并使用调用它 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
       }
    }
    
        2
  •  1
  •   Ryan    12 年前

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

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