在php中将派生类转换为基类 [英] Cast derived class to base class in php

查看:123
本文介绍了在php中将派生类转换为基类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可能在这里遗漏了一些明显的东西,因为这是其他OOP语言的基本功能,但我正在努力用PHP这样做。我知道PHP不是真正的OOP语言,但仍然......

I'm probably missing something obvious here as this is basic functionality in other OOP languages, but I'm struggling with PHP way of doing this. I understand that PHP is not "true" OOP language, but still...

我所追求的是将实例化为派生类的对象转换为基类。类似于:

What I'm after is casting an object instantiated as derived class to base class. Something along the lines of:

class Some{}

class SomeMock extends Some {}

function GetSomeMock(){
  $mock = new SomeMock();
  return (Some)$mock; //Syntax error here
}

我发现了一些有关向下转发的奇怪请求的问题派生的基类对象可能会有一些令人讨厌的调整,但这个基本功能并不一定非常困难。我在这里想念的是什么?

I've found some questions with strange request of downcasting objects of base class to derived which is possible with some nasty tweaks, but this basic functionality does not have to be that difficult. What am I missing here?

编辑:似乎总是很重要我想要实现的目标。没问题。 GetSomeMock()是一个工厂方法,它将返回一个模拟对象存根(从基类派生,所有属性在构造函数中预先填充)具有预期的属性值。然后我将它与从数据库恢复的另一个基类型对象进行比较:

It seems that it's always matter what I'm trying to achieve. No problem. GetSomeMock() is a factory method that would return a mock object stub (derived from base class, all properties prepopulated in constructor) with expected properties' values. I would then compare it to another object of base type that is restored from database:

$this->assertEquals($mockObject, $realObject);

由于$ mockObject和$ realObject属于不同类型,因此立即失败。我可以想象我可以实现相同的许多变通办法,但我希望尽可能简单。

This fails instantly as $mockObject and $realObject are of different types. I can imagine there are many workarounds I can implement to achieve the same, but I'd like to keep things as simple as possible.

推荐答案

好的,简短的回答似乎是:这是不可能的。 PHP比我更了解我需要什么类型。

Ok, the short answer seems to be: This is not possible. PHP knows better than me what type I need.

这篇关于在php中将派生类转换为基类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆