Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php anonymous class extends dynamic

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)

like image 867
adeptofvoltron Avatar asked Dec 05 '25 03:12

adeptofvoltron


1 Answers

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.

like image 176
Jim Avatar answered Dec 07 '25 17:12

Jim