note 58488 deleted from language.oop5.autoload by joey

From: Date: Thu, 05 Jan 2012 15:29:34 +0000
Subject: note 58488 deleted from language.oop5.autoload by joey
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-185372@lists.php.net to get a copy of this message
Note Submitter: quetzalcoatl(AT)poczta.fm ---- While __autoloading is a nice feature, one can stumble upon small problem with it. Imagine: file A.php: <? function __autoload($cname) { require_once "include/$cname.php";} } B::testC(); ?> file B.php: <? function __autoload($cname) { require_once "include/$cname.php";} } class B { public static function test() { C::testMe(); } } ?> file C.php: <? class C { public static function testMe() { print("OK!"); } } ?> Now, running file A.php will result in an error.. because from A's point of view, function __autoload is declared twice - once in A.php, and in required_once'd B.php, too! [Not mentioning that C.php and many many many other required or included files could use it too :) ] So, of course we can remove the duplicate __autoload functions from B.php and any other required files. Thus, we either disallow usage of B.php independently (and other required-able/include-able files!) , as without the __autoload it can not work -- or we have to manually require_once its dependecies, thus making manually the job of __autoload. Irritating, isn't it? A simple trick can help us here. Every file you would place an __autoload function, place instead something like: if(!function_exists("__autoload")) { //your __autoload declaration, for example: function __autoload($cname) { require_once "include/$cname.php"; } } When I first tried it, I was really surprised that you can control functions' declaration with simple IF, without any evals or other tricks. Well.. it's probably a basic "trick", but I didn't notice it anywhere. Feel free to remove it if it was already posted somewhere:)

« previous php.notes (#185372) next »