警告:传递给函数的参数不正确

warning: incorrect argument passed to function

我有一个函数 beforeMarshal () 位于 ModelTable.php。此函数在保存请求数据之前正确执行,但是每次保存数据时我都会收到 php 警告。

public function beforeMarshal(Event $event, ArrayObject $data, ArrayObject $options)
{
    $ip = $data['ip'];
    $data['iplong'] = ip2long($ip);
}

Warning (4096): Argument 1 passed to App\Model\Table\ServersTable::beforeMarshal() must be an instance of App\Model\Table\Event, instance of Cake\Event\Event given

Warning (4096): Argument 2 passed to App\Model\Table\ServersTable::beforeMarshal() must be an instance of App\Model\Table\ArrayObject, instance of ArrayObject given

Warning (4096): Argument 3 passed to App\Model\Table\ServersTable::beforeMarshal() must be an instance of App\Model\Table\ArrayObject, instance of ArrayObject given

如果我将 debug 设置为 false,一切都很好,但这不是一个很好的解决方案。

这可能是一个 namespace 问题。错误是函数想要一个精确类型的对象,它接收了另一个对象。

我假设 beforeMarshal() 是您自己的自定义函数,它位于命名空间 App\Model\Table 中(因为它属于 ModelTable class)。

此外,您可能是从其他文件调用它的,您没有在其中指定命名空间,因此它认为自己在全局命名空间中。

任一

  • 类型提示函数定义中正确的对象类型
  • 全局 use ModelTable.php
  • 中正确的对象类型

精确类型提示

将函数定义更改为:

public function beforeMarshal(\Cake\Event\Event $event, \ArrayObject $data, \ArrayObject $options)

注意反斜杠。他们指示函数在考虑对象类型时从全局命名空间开始。

全球use

在您的 ModelTable.php 脚本(或包含函数的脚本)的最顶部添加:

use
    Cake\Event\Event,
    ArrayObject;

因此在整个脚本中,任何使用 EventArrayObject 类型都将使用正确的类型,而无需每次都指定全名。

选哪个

有意见

我更喜欢在我的脚本顶部使用 use。它可以防止在这个特定脚本中滥用类型,当我必须将 ALL\Templating\Parser 更改为 ALL\Parser 时,我只需在一个地方进行。

每次都指定整个对象命名空间路径很麻烦,而且更容易出错,但可能有好处;自从我开始使用它以来,我没有体验过它们,也没有停止过全局方法。

去掉Event、ArrayObject关键字,简单写成如下:

public function beforeMarshal($event, $data, $options)
{
    $ip = $data['ip'];
    $data['iplong'] = ip2long($ip);
}

希望这能解决您的问题。