Re: RFC: Anonymous Classes

From: Date: Tue, 24 Sep 2013 19:01:09 +0000
Subject: Re: RFC: Anonymous Classes
References: 1 2  Groups: php.internals 
Request: Send a blank email to [email protected] to get a copy of this message
On 24 September 2013 14:51, Nicolas Grekas <[email protected]>wrote:

> What about allowing a "use" statement on these methods?
>
> $someFoo = "bar";
>
> $object = new class{
>     function method() use ($someFoo) { return $someFoo;}
> }
>
> $object->method(); // "bar";
>


I think the idea of anonymous classes is very useful.

a use case that I recently encountered, is to override a specific method in
a class.

So instead of creating a new class that extends the original class, you can
just use an anonymous class and override the methods that you want.

E.G.

You can to the following:

use Symfony\Component\Process\Process;

$process = new class extends Process {
    public function start() {
        /* ... */
    }
};

instead of the following:

namespace My\Namespace\Process;

use Symfony\Component\Process\Process as Base;

class Process extends Base {
    public function start() {
        /* ... */
    }
}


$process = new \My\Namespace\Process\Process;


Thread (55 messages)

« previous php.internals (#69324) next »