wwelvaert Posted December 12, 2007 Share Posted December 12, 2007 I am experiencing a strange problem when I loop through an array of objects: I have a class "input" (html input boxes): ... //Attributes: var $value; function Value() { $value = $_GET[something]; ... $this -> value = $value; return $this -> value; } When I loop through an array of objects using a foreach loop, the function only works if I specifiy each key, it does not work if I use the foreach $input as $key=> object syntax: $fields = array($input[1], ....); $field_keys = arraykeys(...); This works: foreach ($field_keys as $key) { $field[$key] -> Value(); } This does not: foreach ($field as $key => $object) { $object -> Value(); } In the latter implementation, the function works just fine, the variable $object-> value contains the correct information, but the variable $field[...] -> value is NULL. Any information on why this happens is appreciated. BTW, this is on a php 4.3 installation for backward compatibility. Quote Link to comment Share on other sites More sharing options...
davestewart Posted December 12, 2007 Share Posted December 12, 2007 You have your loop key / value variables mixed up: It's either: // 1 argument only looks at the values foreach($array as $value) or // 2 arguments looks at the keys and values foreach($array as $key => $value) As for the rest of your code... are you leaving out a lot of stuff you're not telling us? // this just doesn't make sense, unless $object is an object instantiated from a class, and Value is an instance method of that class (with no arguments). // Also, unless you are using $key, it reads better to omit it // class methods should be lower_case or camelCase (Caps are saved for ClassNames) foreach ($field as $key => $object) { $object -> Value(); } Quote Link to comment Share on other sites More sharing options...
wwelvaert Posted December 12, 2007 Author Share Posted December 12, 2007 Thanks Dave. I did leave out a lot of code (for clarity) as this is a fairly large project. To your point, "$object is an object instantiated from a class, and Value is an instance method of that class" - I should have made that clearer. The array $fields consists of objects of class "input". Quote Link to comment Share on other sites More sharing options...
davestewart Posted December 13, 2007 Share Posted December 13, 2007 Okeydokey Did we solve your problem then? Quote Link to comment Share on other sites More sharing options...
deadimp Posted December 14, 2007 Share Posted December 14, 2007 To do some simple debugging, call print_r() [recursive print] on your foreach iterator and see if it's an object. If it's not a lot of data, post it on here. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.