Php 在子对象中实例化对象;分配给父类变量
正确的方法是什么:Php 在子对象中实例化对象;分配给父类变量,php,class,oop,Php,Class,Oop,正确的方法是什么: // 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;
// 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
}
}
在代码中尝试此操作时,出现以下错误:
致命错误:当不在对象上下文中时使用$this
我做错了什么?(这是指类A
实例)您不能在静态方法中使用$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
}
}
不能在静态方法中使用
$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
}
}
不能使用
$this
在静态方法中引用对象,因此必须对其进行一些更改。使对象
成为受保护的静态成员
class A {
protected static $object;
private static function() {
$object = self::$object;
// use the new instance of $object
}
}
不能使用
$this
在静态方法中引用对象,因此必须对其进行一些更改。使对象
成为受保护的静态成员
class A {
protected static $object;
private static function() {
$object = self::$object;
// use the new instance of $object
}
}
我真不敢相信那个严重的错误。这是一个基本原则。在时间允许的时候给你批改。我真不敢相信那个错误。这是一个基本原则。在时间允许的情况下给你做正确的标记。你有试过吗?!?可能是重复的你有试过吗?!?可能重复的