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)

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
adeptofvoltron
  • 369
  • 1
  • 9
  • 5
    This is obviously not a duplicate since PHP7 offers anonymous classes. http://php.net/manual/en/language.oop5.anonymous.php – Marcel Mar 22 '17 at 19:06
  • you right. anyway looks for me that the answer will be similar. only 'eval' but i don't want to use it... – adeptofvoltron Mar 22 '17 at 19:07
  • Does this answer your question? [PHP Class dynamically extending in runtime](https://stackoverflow.com/questions/48883980/php-class-dynamically-extending-in-runtime) – DigiLive Feb 20 '22 at 07:14

1 Answers1

1

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.

Jim
  • 3,210
  • 2
  • 17
  • 23