Jump to content

php class and array don't play well together.


wwelvaert

Recommended Posts

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.

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();
}

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".

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.