January 5, 2010

193 words 1 min read

PHP: “Only variables can be passed by reference”

`

$dir = "./mydirectory/";

if ($handle = opendir($dir)) {
  while (false !== ($file = readdir($handle))) {
    if (preg_match("/^\..*/",$file,$junk) || preg_match("/^BAD.*/",$file,$junk) || preg_match("/^TEST.*/",$file,junk){
      //Skip it
      print "Skip: $file\n";
    }else{
      //We want to edit this file
      print "--EDITING--: $file\n";
    }
  }
  closedir($handle);
}
?>

`

This isn’t exactly the most complicated piece of code, but it was extremely annoying when I got the error “Only variables can be passed by reference” back from PHP. Getting this error really made me miss Perl again. Perl’s interpreter had the most fantastic error catching. It would (generally) tell you what the error was in language that was very easy to understand, and in some cases even suggest the fix (Like you forgot a semicolon on line X). PHP on the other hand, loves these damned messages that make no sense.

So what’s wrong here? The preg_match line, the final “$junk” is actually just “junk”. I forgot the string symbol ($). Very simple issue, very easy to fix… but very difficult to find information on. Normally a quick google reveals all, but for this error… Nada. So if you happen to google this error and land here, hopefully this solves your issue.