How to dynamically create an anonymous class that extends an abstract class in PHP?

7.8k Views Asked by At

Simply, let me explain by an example.

<?php
class My extends Thread {
    public function run() {
        /** ... **/
    }
}
$my = new My();
var_dump($my->start());
?>

This is from PHP manual.

I am wondering if there is a way to do this in more Java-like fashion. For example:

<?php
$my = new Thread(){
        public function run() {
            /** ... **/
        }
      };
var_dump($my->start());
?>
4

There are 4 best solutions below

0
On

I know this is an old post, but I'd like to point out that PHP7 has introduced anonymous classes.

It would look something like this:

$my = new class extends Thread
{
    public function run()
    {
        /** ... **/
    }
};

$my->start();
0
On

Or you can just use namespaces.

<?php
namespace MyName\MyProject;
class Thread {
   public function run(){...}
}
?>


<?php
use MyName\MyProject;
$my = new Thread();

$my->run();
0
On

You do have access ev(a|i)l. If you used traits to compose your class it COULD be possible to do this.

<?php
trait Constructor {
  public function __construct() {
    echo __METHOD__, PHP_EOL;
  }
}

trait Runner {
  public function run() {
    echo __METHOD__, PHP_EOL;
  }
}
trait Destructor {
  public function __destruct() {
    echo __METHOD__, PHP_EOL;
  }
}

$className = 'Thread';
$traits = ['Constructor','Destructor','Runner',];
$class = sprintf('class %s { use %s; }', $className, implode(', ', $traits));
eval($class);
$thread = new $className;
$thread->run();

This outputs ...

Constructor::__construct
Runner::run
Destructor::__destruct

So you CAN, but not sure if you SHOULD.

1
On