|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2016-05-17 20:13 UTC] nickdnk at hotmail dot com
Description:
------------
Hello
If passing a variable (let's say a stdClass) to the foreach method, it does not produce an error. It silently does not loop the object (since it cannot).
I'm no expert, but I'd say that at least a warning should be raised if trying to iterate a non-array object. I'm sorry if this is intentional, but I do believe an error was raised in 5.6.
Test script:
---------------
$obj = new stdClass();
foreach ($obj as $anObj) {
error_log("nothing is output here, obviously, but no error either");
}
Expected result:
----------------
I expect an error or warning to occur, since I'm traversing a non-array.
Actual result:
--------------
Nothing happens at all.
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Sat Nov 08 17:00:02 2025 UTC |
I don't know how to edit the documentation to alleviate this problem as I don't know when or why you'd ever knowingly use foreach on a non-array object, hence the original bug report. Consider the following: class SomeClass { private $anArray; public function getArray() { return $this->anArray; } } I left out constructor etc, but assume the private variable contains a valid array, that our class has been instantiated and that it is referenced by a variable, let's call it $ourClass. Now somewhere in our code we *accidentally* do this: foreach ($ourClass as $anObject) { *do something with $anObject* // Nothing happens } Instead of the correct approach: foreach ($ourClass->getArray() as $anObject) { *do something with $anObject* // Something happens } Now our code silently fails. I realize this is a programmer's error, but are warnings and such not meant to help us avoid errors that are *always* errors? That's why I wanted an example of when the first approach is ever sensible, as in; is it ever not an error? If not, why not warn the user that he is doing something senseless? If yes, please provide an example. Or does it have something to do with speed - as in having to check for this every time foreach is used? Thanks :)