如何在PHP中从构造函数返回子类
这不起作用,因为newsuper将是一个空的Super对象,所有成员都为NULL。PHP不允许分配给$this,因此$this=new Sub也不起作用如何在PHP中从构造函数返回子类,php,oop,Php,Oop,这不起作用,因为newsuper将是一个空的Super对象,所有成员都为NULL。PHP不允许分配给$this,因此$this=new Sub也不起作用 我知道正确的模式应该是这里的工厂。但这需要对代码进行大量修改,所以我想知道是否有可能这样做。既然Sub是超级的,我不明白为什么从OOP的角度来看它不应该受到限制。你在这里出了点问题。构造函数没有返回值,您无法从构造函数返回实例-一旦调用构造函数,类被解决,您就不能再更改它 您要做的是实现以下功能: <?php class Super {
我知道正确的模式应该是这里的工厂。但这需要对代码进行大量修改,所以我想知道是否有可能这样做。既然Sub是超级的,我不明白为什么从OOP的角度来看它不应该受到限制。你在这里出了点问题。构造函数没有返回值,您无法从构造函数返回实例-一旦调用构造函数,类被解决,您就不能再更改它 您要做的是实现以下功能:
<?php
class Super {
public $my;
public function __construct ( $someArg ) {
$this->my = $someArg;
}
public static function factory ($somearg) {
if ( class_exists('Sub') && $somearg["foo"] == "bar") { // or some other condition
return new Sub( $someArg );
}
else {
return new Super($someArg);
}
}
}
class Sub extends Super {}
$mynewsuborsuper = Super::factory($myargs);
?>
您不能将$this赋值,也不能从构造函数返回任何内容。使用PHP反射。使用工厂时不需要开关或继承
<?php
class DocumentFactory
{
public function create($className, $constructorArguments = array())
{
$reflection = new ReflectionClass($className);
return $reflection->newInstanceArgs($constructorArguments);
}
}
abstract class Document
{
$protected $doc;
public function __construct($string){$this->doc = $string;}
}
class XMLDocument extends Document
{
public function __construct($string, $extraArg)
{
parent::__construct($string);
//Do something else with $extraArg
}
}
class HTMLDocument extends Document
{
}
$DFactory = new DocumentFactory();
$XMLDocument = $DFactory->create('MY\FULL\NAMESPACE\XMLDocument', array(//extra arguments));
//Or add .php at the end if you're not using namespaces
它应该受到限制,因为Sub依赖于Super,但是Super不应该知道Sub的任何内容。你刚才在那里创建了一个循环依赖项。嗯,我明白你的意思,但是工厂模式不也有同样的依赖项吗?工厂通常不会返回它自己的子类。factory类可能依赖于它所制造的类,但to build类不依赖于factory。