正确的方法是什么:
// 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
}
}