12

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());
?>
jlai
  • 909
  • 1
  • 10
  • 17
  • 1
    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) – Alma Do Aug 16 '13 at 14:14
  • Welcome to PHP. It does not support such behaviour. The only way to do it is the first way. – baldrs Aug 16 '13 at 14:20

4 Answers4

17

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();
Thomas Kelley
  • 10,187
  • 1
  • 36
  • 43
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

Richard A Quadling
  • 3,769
  • 30
  • 40
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.

Richard A Quadling
  • 3,769
  • 30
  • 40
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();
Raul3k
  • 141
  • 5