note 75412 modified in function.ArrayObject-offsetUnset by danbrown

From: Date: Fri, 28 Nov 2008 22:02:01 +0000
Subject: note 75412 modified in function.ArrayObject-offsetUnset by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-147294@lists.php.net to get a copy of this message
Be careful when you are working with collections. This method works with the reference of an array instead of its retrieved value. So, you can do a mistake. In order to understand have a look at code as follow: <?php class Employee { public function __construct() { } } class Company { private $arrEmployee; public function __construct() { } public function AddEmployee(Employee $oEmployee) { $this->arrEmployee[] = $oEmployee; } public function getEmployeeList() { return $this->arrEmployee; } } ?> <?php // first, creates the Company object $oCompany = new Company(); // second, add 10 elements in foreach( range(0, 9) as $index ) { $oCompany->AddEmployee( new Employee() ); } // get them $arrEmployee = $oCompany->getEmployeeList(); // creates an ArrayObject from "$arrEmployee" $arrayobject = new ArrayObject($arrEmployee); // unsets its firt five elements foreach( range(0, 4) as $index ) { $arrayobject->offsetUnset($index); } // get them again $arrEmployee = $oCompany->getEmployeeList(); // it shows just 5 elements, they were removed as reference via "offsetUnset" method print_r($arrEmployee) ; ?> --was-- Be careful when you are working with collections. This method works with the reference of an array instead of its retrieved value. So, you can do a mistake. In order to understand have a look at code as follow: <?php class Employee { public function __construct() { } } class Company { private $arrEmployee; public function __construct() { } public function AddEmployee(Employee $oEmployee) { $this->arrEmployee[] = $oEmployee; } public function getEmployeeList() { return $this->arrEmployee; } } ?> <?php // first, creates the Company object $oCompany = new Company(); // second, add 10 elements in foreach( range(0, 9) as $index ) { $oCompany->AddEmployee( new Employee() ); } // get them $arrEmployee = $oCompany->getEmployeeList(); // creates an ArrayObject from "$arrEmployee" $arrayobject = new ArrayObject($arrEmployee); // unsets its firt five elements foreach( range(0, 4) as $index ) { $arrayobject->offsetUnset($index); } // get them again $arrEmployee = $oCompany->getEmployeeList(); // it shows just 5 elements, they were removed as reference via "offsetUnset" method print_r($arrEmployee) ; ?> http://php.net/manual/en/function.ArrayObject-offsetUnset.php

« previous php.notes (#147294) next »