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

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

希望能帮助到你!

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...