note 112643 added to functions.arguments
| From: | ravenswd at gmail dot com | Date: | Mon, 08 Jul 2013 14:30:16 +0000 |
| Subject: | note 112643 added to functions.arguments | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-195503@lists.php.net to get a copy of this message | ||
Be careful when passing arguments by reference, it can cause unexpected side-effects if one is not
careful.
I had a program designed to sweep through directories and subdirectories and report on the total
number of files, and the total size of all files. Since it needed to return two values, I used
variables passed by reference.
In one spot in the program, I didn't need the values of those variables after they were
returned, so I just used a garbage variable named $ignore instead. This caused a curious bug which
took me a while to track down, because the effects of the bug were in a different part of the
program than the place where I had made a mistake.
Since the same variable was used for both parameters passed by reference, they ended up both
pointing to the same physical location in memory, so changing one of them caused both of them to
change. The code below is an excerpt of my program, stripped down to just the few lines necessary to
illustrate what was happening:
<?php
sweep ($ignore, $ignore);
// no errors occur here
function sweep ( &$filecount, &$bytecount ) {
$filecount = 1;
$bytecount = 1024;
print "Files: $filecount - Size: $bytecount"; // prints "Files: 1024 - Size:
1024"
}
?>
----
Server IP: 69.147.83.199
Probable Submitter: 98.226.88.238
----
Manual Page -- http://php.net/manual/en/functions.arguments.php
Edit -- https://master.php.net/note/edit/112643
Del: integrated -- https://master.php.net/note/delete/112643/integrated
Del: useless -- https://master.php.net/note/delete/112643/useless
Del: bad code -- https://master.php.net/note/delete/112643/bad+code
Del: spam -- https://master.php.net/note/delete/112643/spam
Del: non-english -- https://master.php.net/note/delete/112643/non-english
Del: in docs -- https://master.php.net/note/delete/112643/in+docs
Del: other reasons-- https://master.php.net/note/delete/112643
Reject -- https://master.php.net/note/reject/112643
Search -- https://master.php.net/manage/user-notes.php