Thursday, 15 July 2010

php - Inline interface implementation - Implement interface methods at declaration -



php - Inline interface implementation - Implement interface methods at declaration -

i come java, can this:

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 performaction method } }; action.performaction(); //will execute implemented method } }

as can see, i'm not creating class implements action, i'm implementing interface straight on declaration.

is possible php?

what i've tried:

action.php:

<?php interface action { public function performaction(); } ?>

myactions.php:

include "action.php"; $action = new action() { public function performaction() { //do stuff } };

what get:

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

so, question is: possible php? how should it?

no, can't. php doesn't offer anonymous classes java does. can seek simulate behaviour want, results be...mixed @ best.

here's code:

interface action { public function performaction(); } class myclass { public function methodone($object) { $object->performaction(); // can't phone call straight - 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); // 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

hope helps!

php oop interface declaration implementation

No comments:

Post a Comment