【发布时间】:2018-04-25 20:09:36
【问题描述】:
我从这种情况中得到了很好的笑声。它在一个巨大的应用程序中,所以我不能只上传所有内容,但这里是我的代码的本地相关部分:
```
public function reallyCustomSort($thing, $options='')
{
die('dying. gettype results for our param: '.gettype($thing));
//Gives us "array." So why does usort complain about "object given?"
die('dying. get_class results for our param: '.get_class($thing)); // Gives us "get_class() expects parameter 1 to be object, array given.
usort($thing, 'AppBundle\Twig\CustomSort::customCompare'); // Gives us "Warning: usort() expects parameter 1 to be array, object given"
die('We are done here.');
return($thing);
}
public function someRandomFunction($thing){
die('dying in someRandomFunction. gettype results for our param: '.gettype($thing)); //Gives us "array."
}
```
换句话说,分析我的变量的两个函数调用都同意它是一个数组,然后在一行之后,我的 usort() 函数认为该变量包含一个对象。
以前有没有人遇到过这种行为?如果是这样,您是如何解决的?
我已经尝试过的一些事情:
插入 sleep() 调用以查看是否涉及竞争条件。 (看 要点如下。)不走运。
将
$thing变量传递给不同的函数只是为了查看是否 出于某种奇怪的原因,仅仅将$thing传递给了 函数导致转换。运气不好。清除我的应用程序中的各种缓存。没有运气。
带有更多(注释掉)代码的要点,展示了我尝试过的事情:
https://gist.github.com/patrickmaynard/7c3c7f0695e223e6903fd729172b4c21
【问题讨论】:
-
很难说发生了什么,没有发生什么,因为很多代码都被注释掉了。你能提供一个例子,只显示真正重要的行吗?
-
另见:php.net/manual/en/language.references.pass.php ~ 确保您正在使用的数据没有被“通过引用”操纵,这可能会导致这样的混乱。
-
usort()确实“通过引用”工作,但它不会将数组转换为对象,所以我认为这不是问题的根源。在您致电usort()之前,它已经发生在某处。 -
好点。我将尝试定义一个通过引用接收变量的测试函数。也许只是通过引用传递的行为在这里发挥了作用。 (更新:不,这不是问题。正如您所怀疑的,它在其他地方。)感谢您之前的回答,顺便说一句——我继续按照您的建议清理了 sn-p。好电话。
标签: php arrays object type-conversion usort