【问题标题】:Send class definition to function in PHP将类定义发送到 PHP 中的函数
【发布时间】:2012-11-19 09:14:35
【问题描述】:

我正在尝试在 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";
  }
});

有什么想法或见解?

提前致谢

编辑

我知道我可以扩展 Action 并覆盖我想要的函数,然后将新类作为参数传递。我正在尝试做的是模仿 Java 中通常所做的事情,只需使用重写的方法发送原始类,因此我不必创建一个全新的类,只需将其传递给一个函数。

编辑

我想到了一种有点笨拙的方法,但使用闭包可以满足我的需要:

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";}));

不过,我的主要目标是模仿在 Java 中完全相同的行为,我可以在其中动态覆盖多个方法...仍然欢迎想法和/或见解。

【问题讨论】:

  • 男孩,这是一团糟。我认为您需要阅读更多关于 OOP 的内容。您正在构建参数定义-这是不行的。您的语法错误是因为您将构造函数视为函数,它应该在 new Action() 之后停止并关闭。
  • 但是我想发送一个具有不同 doit() 函数的 Action 实例(因此被覆盖),所以我不想通过 perform(new Action()) 传递类执行。
  • 然后给函数传入参数,处理里面的逻辑。你不能只是动态地创建方法——没有必要,有一百种方法可以按照惯例来完成。下面的答案是最传统的 IMO。

标签: php oop function arguments overriding


【解决方案1】:
class ExtendedAction extends Action {

    public function doit() {
        return "Custom action";
    }

}

$ap->perform(new ExtendedAction);

你必须声明一个常规的新类,它可以extend你的基类。您不能像正在尝试的那样即时执行此操作。

我正在尝试做的是模仿 Java 中通常所做的事情,然后只发送带有重写方法的原始类...

这在 PHP 中是不可能的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-10
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    相关资源
    最近更新 更多