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
希望能帮助到你!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。