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

Just let me explain with an example.

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

This is from the PHP manual.

I am wondering if there is a way to make this more like Java. For instance:

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

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

It will look something like this:

 $my = new class extends Thread { public function run() { /** ... **/ } }; $my->start(); 
+2
source

Or you can just use namespaces.

 <?php namespace MyName\MyProject; class Thread { public function run(){...} } ?> <?php use MyName\MyProject; $my = new Thread(); $my->run(); 
+1
source

You have access ev (a | i) l. If you used traits to create your class, you MAY be able 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(); 

These outputs ...

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

So, you CAN, but not sure, YOU SHOULD.

0
source

Source: https://habr.com/ru/post/1497443/


All Articles