我来自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可以这样吗?我该怎么办?
答案 0 :(得分:2)
以下是一些代码:
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
希望它有所帮助!
答案 1 :(得分:2)
使用PHP 7,anonymous classes可以实现这一点。
$action = new class implements Action() {
public function performAction() {
//do some stuff
}
};