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.
Ok, the short answer seems to be: This is not possible. PHP knows better than me what type I need.
In PHP you cannot cast to a specific class, I cannot even see any need for that.
You may cast to some native type - string
, int
, array
, object
. But not a specific class.
If you need to use some functionality of a base class, you can do it via parent
keyword.
class Some {
public function execute(){
echo "I am some" ;
}
}
class SomeMock extends Some {
public function execute(){ //Override the function
parent::execute() ; //Here you can execute parent's functionality and add some more
}
}
Edit:
instanceof
operator may come handy. When comparing objects.
For instance:
$object = new SomeMock() ;
$status = ($object instanceof Some && $object instanceof SomeMock); //will return true here ;
Child classes inherit non-private properties and methods.
Let's say, you have your function:
function assertEquals($mockObject, $realObject){
if ($mockObject instanceof Some && $realObject instanceof Some){
//Both objects have the same base class - Some
//That means they must have inherited the functionality and properties of Some class.
}
}
You can do it with an custom function:
private function castParameter(BaseClass $parameters) : DerivedClass {
return $parameters;
}
I did come across use cases when I needed to cast a derived class to its base class. I did the following.
function castToParentClass($derivedClassInstance) {
$parentClassName = get_parent_class($derivedClassInstance);
$parentClassInstance = new $parentClassName();
foreach ($parentClassInstance as $key => $value) {
$parentClassInstance->{$key} = $derivedClassInstance->{$key};
}
return $parentClassInstance;
}