Zend PHP5 Certification Study Guide Annoyance
April 18th, 2009 by Ray in Computer Related, PHP/MySQL, The Bin | Tags: php, rant | 3 CommentsZend PHP5 Certification Study Guide by Davey Shafik annoys me in many ways which include grammatical errors and erroneous coding examples.
Today’s rant will be on coding examples:
Page 133.
function __autoload($class)
{
//Require PEAR-compatible classes
require_once str_replace("_", "/", $class);
}
$obj = new Some_Class();
At first glance this looks OK but the author goes on to state that the file, Some/Class.php will be included automagically. WRONG! Autoload passes in the name of the class, not the name of the class plus .php at the end (which is what he is thinking). $class is really Some_Class, so the code above should read:
function __autoload($class)
{
//Require PEAR-compatible classes
require_once str_replace("_", "/", $class) . '.php';
}
$obj = new Some_Class();
I’m annoyed not just because the code is wrong, but because he says “When instantiating Some_Class, __autoload() is called and passed “Some_Class.php” as its argument.” If Mr. Shafik took just a couple of minutes to read the documentation, he would have realized he was wrong, and I could avoid some frustration this book has (and still is) caused me.
It’s also pointless to use require_once inside of __autoload().
Not sure if I agree that it is pointless. If you are only using __autoload for your project, then I suppose include() would suffice. However, if you have a large project w/legacy code that uses requires and includes in different places, require_once would be a safe bet. Actually, I use require_once on most (if not all) of my included files just to play it safe.