faqts : Computers : Programming : Languages : PHP : kms : Classes

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

37 of 48 people (77%) answered Yes
Recently 7 of 10 people (70%) answered Yes

Entry

How does PHP handle arrays of objects?

Jul 8th, 1999 09:57
Eric van der Vlist, Nathan Wallace,


<?
class top {  
    var $top_id;
    function top($id) {
      $this->top_id = $id;
    }
    function test() {
      $this->top_id -= 12;
      return $this->top_id;
    }
}
// You can create the array of objects
$foo   = array();
$foo[] = new top(12);
$foo[] = new top(23);
// But this wouldn't work as expected.
// echo $foo[1]->top_id;
// Neither would this
// echo $foo[0]->test();
// so will this
$tmp = $foo[0];
echo $tmp->test()."\n";
// But keep in mind that a copy has been created and assigned to $tmp.
//
// In this example, the copy has been updated by the test method, 
// not the orginal object ($foo[0]) as can be checked by repeteting 
// the sequence :
$tmp = $foo[0];
echo $tmp->test()."\n";
// If you want to update the original object, you need to reassign it :
$foo[0] = $tmp;
// which may be time and memory consuming for big and complex objects.
// Another solution is to use the ability of PHP to pass arguments
// to function by reference :
function test_top(&$obj){
	return ($obj->test());
}
echo test_top(&$foo[0])."\n";
echo test_top(&$foo[0])."\n";
echo test_top(&$foo[0])."\n";
// is not very OO but will do the trick.
?>
PHP objects are best dealt with using a "Keep It Simple" philosophy...