Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inline interface implementation - Implement interface methods at declaration

I come from java, where we can do something like this:

Action.java:

public interface Action {
    public void performAction();
}

MainClass.java:

public class MainClass {
    public static void main(String[] args) { //program entry point
        Action action = new Action() {

            public void performAction() {
                // custom implementation of the performAction method
            }

        };

        action.performAction(); //will execute the implemented method
    }
}

As you can see, I'm not creating a class which implements Action, but I'm implementing the interface directly on declaration.

Is something like this even possible with PHP?

What I've tried:

action.php:

<?php

interface Action {

    public function performAction();
}

?>

myactions.php:

include "action.php";

$action = new Action() {

    public function performAction() {
        //do some stuff
    }
};

What I get:

Parse error: syntax error, unexpected '{' in myactions.php on line 3

So, my question is: is something like this possible with PHP? How should I do it?

like image 629
BackSlash Avatar asked Sep 12 '26 11:09

BackSlash


1 Answers

With PHP 7, this has become possible with anonymous classes.

$action = new class implements Action() {
    public function performAction() {
        //do some stuff
    }
};
like image 159
demonkoryu Avatar answered Sep 14 '26 01:09

demonkoryu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!