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

我来自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

希望能帮助到你!

上一篇:ArcGIS Runtime API For Android Kotlin 版入门


下一篇:java-扩展Graphics2D类而不实现所有方法