By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,722 Members | 1,874 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,722 IT Pros & Developers. It's quick & easy.

PHP's References

P: n/a
I'm trying to create a stack of class objects; but on cycling through them
with 'foreach' I am unable to update their properties. What is the correct
method for this?
Jul 16 '05 #1
Share this Question
Share on Google+
3 Replies


P: n/a
ba***@blues.no wrote:
I'm trying to create a stack of class objects; but on cycling through them
with 'foreach' I am unable to update their properties. What is the correct
method for this?


You get copies with foreach; use the key value to access the
original array:

foreach ($foo as $bar->$baz)
{
$foo[$bar] = new MyClass($baz->Name, $baz->WidgetCount);
}

HTH

You really could have thought of this one yourself and tried the code, you
know!

Jul 16 '05 #2

P: n/a
ba***@blues.no schrieb:
I'm trying to create a stack of class objects; but on cycling through them
with 'foreach' I am unable to update their properties. What is the correct
method for this?


foreach() uses a copy of the array. Use somthing like:

<?php
foreach($arr as $key=>$val) {
$arr[$key] = editfunc($val);
}
?>

or for very large arrays

<?php
reset($arr);
while(list($key,$val) = each($arr)) {
$arr[$key] = editfunc($val);
}
?>

Regards
Thomas

Jul 16 '05 #3

P: n/a
Thanks to both Thomas and matty; I actually was unaware of the second form
of 'foreach'. So ended up doing something like the following (which even
keeps me from having to use references.) I'd like to ask one more thing; is
the call to array_keys, neglible in effeciency compared to using the second
form of 'foreach'?

class Foo
{
var $some_value;

function Bar()
{
$this->some_value = "def";
}

function Foo()
{
$this->some_value = "abc";
}
}

$class_stack = array();
array_push( $class_stack, new Foo() );
array_push( $class_stack, new Foo() );

// $some_value is set to "abc"

foreach( $class_stack as $cls=>$key )
{
$class_stack[ $cls ]->Bar();
}

// $some_value now equals "def"
Jul 16 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.