I’m trying to accomplish something like the following in PHP:
// Some interface type thing
class Action {
// Meant to be overridden
public function doit(){ return null; }
}
class ActionPerformer {
public function perform(Action $action) {
$action->doit();
}
}
$ap = new ActionPerformer();
// *** What I'm trying to do/simulate *** //
//
// But returns: Parse error: syntax error, unexpected '{' in
// <file> on line 19
//
$ap->perform(new Action(){ // <-- This is line #19
@Override
public function doit() {
return "Custom action";
}
});
Any ideas or insights?
Thanks in advance
Edit
I know I can just extend Action and override the function I want, then pass the new class as the argument. What I’m trying to do is mimic what is commonly done in Java and just send in the original class with the overridden methods, so I don’t have to create a whole new class just to pass it once to the one function.
Edit
I’ve thought of a way that is a bit clunky, but does just what I needed using a closure:
class Action {
private $isOverridden;
private $func;
public function __construct($func = null) {
$this->isOverridden = false;
if (!is_null($func)) {
$this->isOverridden = true;
$this->func = $func;
}
}
// Meant to be overridden
public function doit(){
if ($this->isOverridden)
return $this->func->__invoke();
return "='(";
}
}
// class ActionPerformer remains the same
$ap = new ActionPerformer();
echo $ap->perform(new Action(function(){ return "=)";}));
echo $ap->perform(new Action(function(){ return "=|";}));
echo $ap->perform(new Action(function(){ return "=P";}));
echo $ap->perform(new Action(function(){ return "=O";}));
Still, my main goal is to mimic the exact same behavior as in Java, where I could override multiple methods dynamically… Ideas and/or insights are still welcome.
You have to declare a regular new class, which can
extendyour base class. You cannot do this on the fly like you’re trying.And that’s not possible in PHP.