anyone of you know how to get effect like in these code
public function create(SomeInterface $obj)
{
$class = get_class($obj);
return new class extends $class {
//some magic here
}
}
Obvious that code will not work in PHP.
$obj can be an instance of many different classes. I want to get an instance of class extending the $obj. (It will give me an ability to overload some basic methods)
It is very possible with PHP 7+. Here is a really simple example:
interface SomeInterface {};
class one implements SomeInterface {};
class two extends one {};
function create(SomeInterface $class) {
$className = get_class($class);
return eval("return (new class() extends $className {});");
}
$newTwoObj = create(new two());
Note that this is returning a new instance of the anonymous object. I don't believe there is any way to return a reference to the class (not instantiated).
Also note that this uses the eval() function, which I don't normally condone, but it is the only way I was able to find have a dynamically-assigned inheritance (without using class_alias() which could only be used once). You will want to be very careful and not allow unsanitized data to be passed in.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With