内联接口实现-在声明时实现接口方法

反斜杠

我来自Java,在这里我们可以执行以下操作:

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
    }
}

如您所见,我没有创建实现的类Action,而是在声明时直接实现了接口。

这样的事情甚至可以用PHP实现吗?

我尝试过的

action.php:

<?php

interface Action {

    public function performAction();
}

?>

myactions.php:

include "action.php";

$action = new Action() {

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

我得到的是:

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

因此,我的问题是:PHP可能会发生这种情况吗?我该怎么办?

莫塔内卢

不行不行 PHP不像Java提供匿名类。但是,您可以尝试模拟所需的行为,但是结果将……最好混合在一起。

这是一些代码:

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

希望能帮助到你!

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章