【问题标题】:Syntax error when trying to create array of anonymous functions [closed]尝试创建匿名函数数组时出现语法错误[关闭]
【发布时间】:2013-06-25 17:18:14
【问题描述】:

我正在尝试实现自己的 MVC 框架,并发明了一种非常好的方法来提供虚拟字段和附加关系的定义。

根据 stackoverflow 上其他一些高票的帖子,这实际上应该有效:

class User extends Model {

  public $hasOne = array('UserSetting');

  public $validate = array();

  public $virtualFields = array(
      'fullname' => function () {
          return $this->fname . ($this->mname ? ' ' . $this->mname : '') . ' ' . $this->lname;
      },
      'official_fullname' => function () {

      }
  );
}

但它不起作用。它说:解析错误:语法错误,意外的 T_FUNCTION。我做错了什么?

PS。说起这个Can you store a function in a PHP array?

【问题讨论】:

  • 不,我已经检查过了。现在是 5.3.8。
  • 类定义中的属性声明只能是constant values, not expressions.。并且匿名函数根本不是原始类型或结构。

标签: php anonymous-function


【解决方案1】:

您必须在构造函数或其他方法中定义方法,而不是直接在类成员声明中。

class User extends Model {

  public $hasOne = array('UserSetting');

  public $validate = array();

  public $virtualFields = array();

  public function __construct() {
     $this->virtualFields = array(
        'fullname' => function () {
            return $this->fname . ($this->mname ? ' ' . $this->mname : '') . ' ' . $this->lname;
        },
        'official_fullname' => function () {

        }
    );
  }
}

虽然可行,但 PHP 的魔术方法 __get() 更适合此任务:

class User extends Model {

  public $hasOne = array('UserSetting');

  public $validate = array();

  public function __get($key) {
     switch ($key) {
       case 'fullname':
           return $this->fname . ($this->mname ? ' ' . $this->mname : '') . ' ' . $this->lname;
       break;

       case 'official_fullname':
         return '';
       break;
    };
  }
}

【讨论】:

  • 成功了。谢谢你。然而,有点遗憾,因为它不像我最初的想法那样清晰和优雅。也因为我的构造函数有点复杂,可以接受更多的参数,这些参数必须通过 parent::__construct 传递。但是,它仍然很酷。再次感谢。我 +1 编辑了它。
  • @BarthZalewski 你可以考虑看看 PHP 的魔法方法,__get()__call()__callStatic()。这些方法更适合这种事情,并且会让你的构造函数保持干净。 php.net/manual/en/language.oop5.magic.php
猜你喜欢
  • 2023-03-09
  • 1970-01-01
  • 2012-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-12
  • 1970-01-01
  • 2015-02-04
相关资源
最近更新 更多