3

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?

0

2 Answers 2

5

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

$action = new class implements Action() {
    public function performAction() {
        //do some stuff
    }
};
Sign up to request clarification or add additional context in comments.

Comments

2

No, can't. PHP doesn't offer anonymous classes like Java does. You can however try to simulate the behaviour you want, but the results will be...mixed at best.

Here's some code:

interface Action
{
    public function performAction();
}

class MyClass
{
    public function methodOne($object)
    {
        $object->performAction(); // can't call directly - fatal error

        // work around
        $closure = $object->performAction;
        $closure();
    }

    public function methodTwo(Action $object)
    {
        $object->performAction();
    }
}

$action = new stdClass();
$action->performAction = function() {
    echo 'Hello';
};

$test = new MyClass();
$test->methodOne($action); // will work
$test->methodTwo($action); // fatal error - parameter fails type hinting

var_dump(method_exists($action, 'performAction')); // false
var_dump(is_callable(array($action, 'performAction'))); // false

Hope it helps!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.