CakePHP 3.7:函数名称必须是字符串

时间:2019-05-17 10:48:12

标签: cakephp-3.7

我在UsersController中有一个方法

    public function addMailbox($data)
    {
              $this->LoadModel('Mailbox');
              $mailbox = $this->Mailbox->newEntity();
              $mailbox->username = $data('username');
              $mailbox->name = $data('name');

        if ($this->Mailbox->save($mailbox)) {
            return $this->redirect(['action' => 'index']);
            }
        $this->Flash->error(__('Error'));
       }

,将代码粘贴到add()方法中即可正常工作,但是在使用后

     $this->addMailbox($this->request->getData());

我所得到的只是 错误:函数名称必须是字符串

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

使用PHP访问数组时语法错误,请使用方括号:

$mailbox->username = $data['username'];
$mailbox->name = $data['name'];

以这种方式,它正在尝试使用$data中命名的变量调用函数,但是$ data是一个数组而不是字符串(有关更多信息,请参见Variable functions

此外,您不应直接在$ mailbox属性上设置用户输入-这会绕过验证。相反,只需将$ data粘贴在newEntity()中:

public function addMailbox($data)
{
    $this->loadModel('Mailbox'); // This also is not required if this function is inside the MailboxController
    $mailbox = $this->Mailbox->newEntity($data);

    if ($this->Mailbox->save($mailbox)) {
        return $this->redirect(['action' => 'index']);
    }
    $this->Flash->error(__('Error'));
}