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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?