php anonymous class extends dynamic
Asked Answered
C

1

19

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)

Catholic answered 22/3, 2017 at 18:40 Comment(3)
This is obviously not a duplicate since PHP7 offers anonymous classes. php.net/manual/en/language.oop5.anonymous.phpNonfeasance
you right. anyway looks for me that the answer will be similar. only 'eval' but i don't want to use it...Catholic
Does this answer your question? PHP Class dynamically extending in runtimeClownery
E
2

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.

Expiable answered 31/12, 2021 at 2:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.