After writing this post a few weeks ago about PHP references, I realized I missed one great use for references. The example scenario is this, you have an array of array’s representing rows returned from a database. You want to convert these arrays to specialized objects quickly and easily.
1 2 3 4 5 | $rows = $this->findRows(); foreach($rows as &$row){ $row = new RowObject($row); } |
Basically, what is happening is we are referencing the $row reference in the foreach loop. The reason this must be done is because we want the actual $rows array to change, so we have to change all the references in it.