PHP 5.1.6 迭代对象时出现 ArrayAccess 错误
我必须在 PHP 5.1.6 上开发一个网站,而我刚刚在我的网站中遇到了一个错误,而在 5.2+ 上不会发生该错误。使用 foreach() 迭代对象时,出现以下错误:“致命错误:在后/前增量/减量中用作数组的对象必须通过引用返回值...”
有谁知道如何解决此问题?
$f_type = new Feeding_type_Model;
$f_type->type = $post['feeding_type'];
$f_type->quantity = $post['quantity'];
$f_type->feeding_id = $feed->id;
$f_type->save();
if (strpos($post['feeding_type'], 'comm'))
{
foreach ($post['commercial_brands'] as $brand)
{
$comm_food = new Commercial_food_Model;
$comm_food->brand = $brand;
$comm_food->feeding_type_id = $f_type->id;
$comm_food->save();
}
}
I'm having to develop a site on PHP 5.1.6 and I've just come across a bug in my site which isn't happening on 5.2+. When using foreach() to iterate over an object, I get the following error: "Fatal error: Objects used as arrays in post/pre increment/decrement must return values by reference..."
Does anyone know how to get around this issue?
$f_type = new Feeding_type_Model;
$f_type->type = $post['feeding_type'];
$f_type->quantity = $post['quantity'];
$f_type->feeding_id = $feed->id;
$f_type->save();
if (strpos($post['feeding_type'], 'comm'))
{
foreach ($post['commercial_brands'] as $brand)
{
$comm_food = new Commercial_food_Model;
$comm_food->brand = $brand;
$comm_food->feeding_type_id = $f_type->id;
$comm_food->save();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在php文档注释中发现了这个,这似乎是一个bug:
如果你有这样的代码
(据我所知),除非 $y 是一个真正的数组,否则它总是会失败 - 如果 $y 是一个实现 ArrayAccess 的对象,它就无法工作。如果您的 offsetGet() 函数通过引用返回,则会出现致命错误“MyClass::offsetGet() 的声明必须与 ArrayAccess::offsetGet() 的声明兼容”。但是,如果您尝试让它按值返回,则会出现(矛盾的)致命错误“在后/前递增/递减中用作数组的对象必须按引用返回值”,至少在我的 PHP 版本中是这样。
因此,不可能采用处理数组的任意代码并尝试用自己的对象替换数组,即使所有普通数组函数都没有失败(它们确实失败了,或者至少其中一些函数失败了) )。
Found this in the php documentation comments, it seems to be a bug:
If you have code like
then this will (as far as I can tell) always fail unless $y is a real array -- it cannot work if $y is an object implementing ArrayAccess. If your offsetGet() function returns by reference, you get the fatal error "Declaration of MyClass::offsetGet() must be compatible with that of ArrayAccess::offsetGet()". If you try to have it return by value, however, you get the (contradictory) fatal error "Objects used as arrays in post/pre increment/decrement must return values by reference", at least in my version of PHP.
It is therefore not possible to take arbitrary code dealing with arrays and try to substitute an object of your own for an array, even if all of the normal array functions didn't fail as well (which they do, or at least some of them).