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

4

13

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());
?>
Equities answered 16/8, 2013 at 14:11 Comment(2)
No, you can not act like this way (I suppose there are ways to do this with another syntax and/or constructions, but such way - not)Item
Welcome to PHP. It does not support such behaviour. The only way to do it is the first way.Hymie
S
18

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();
Shilling answered 23/5, 2017 at 21:49 Comment(0)
P
4

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

Plimsoll answered 21/9, 2015 at 10:42 Comment(1)
Starting with PHP7, this is correct ... source: I wrote anonymous class support, and pthreads ...Pyrrhic
P
1

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.

Plimsoll answered 17/9, 2015 at 15:10 Comment(0)
J
1

Or you can just use namespaces.

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


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

$my->run();
Jaffe answered 13/10, 2015 at 15:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.