Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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());
?>
like image 427
jlai Avatar asked Aug 16 '13 14:08

jlai


2 Answers

Alternatively, you can use PHP7's Anonymous Classes capability as documented at http://php.net/manual/en/migration70.new-features.php#migration70.new-features.anonymous-classes and http://php.net/manual/en/language.oop5.anonymous.php

like image 192
Richard A Quadling Avatar answered Oct 20 '22 19:10

Richard A Quadling


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();
like image 16
Thomas Kelley Avatar answered Oct 20 '22 20:10

Thomas Kelley