Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast derived class to base class in php

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?

Edit: 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);

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.

like image 945
Stanislav Kniazev Avatar asked May 09 '13 21:05

Stanislav Kniazev


1 Answers

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

like image 60
Stanislav Kniazev Avatar answered Oct 06 '22 01:10

Stanislav Kniazev