drvvvuyia15070493 2013-06-25 17:18
浏览 19
已采纳

尝试创建匿名函数数组时出现语法错误[关闭]

I am trying to realize my own MVC framework and invented a very nice way to provide definitions of virtual fields and additional relations.

According to some other high-voted post on stackoverflow, this should actually work:

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 () {

      }
  );
}

But it doesn't work. It says: Parse error: syntax error, unexpected T_FUNCTION. What am I doing wrong?

PS. talking about this one Can you store a function in a PHP array?

  • 写回答

1条回答 默认 最新

  • douxie2023 2013-06-25 17:23
    关注

    You must define the methods in the constructor, or some other method, not directly in the class member declaration.

    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 () {
    
            }
        );
      }
    }
    

    While that works, PHP's magic method __get() is better suited to this task:

    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;
        };
      }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器