正如hakre所说,在 PHP 中转换为用户定义的类型本身是不可能的(据我所知)。
您可以做的是在 A 类或 B 类中创建一个方法。例如:
class A
{
public static function fromB( B $object )
{
/* your routine to convert an object of class B to an instance of class A */
}
/* or */
public static function fromA( A $object )
{
/* your routine to convert any object that is a subclass of A to a concrete instance of class A */
}
}
或者
class B
extends A
{
// this method could even be implemented in A already as well actually
public function toA()
{
/* your routine to convert this object to an object of class A */
}
}
在第一个示例中,第一个工厂方法可能会出现问题,因为它要求 A 对特定子类有具体的了解。您需要确定这是否适合您的情况。也许您可以将其抽象为让工厂方法接受从 A 继承的任何对象,例如第二个工厂方法。
在第二个例子中,B 自动知道 A,因为它继承自它。这可能更可取。但是想想看,这甚至可以在 A 中实现,这样该方法就已经在 A 的所有子类中自动可用。