note 58488 added to language.oop5.autoload
| From: | (AT) | Date: | Sat, 05 Nov 2005 23:21:22 +0000 |
| Subject: | note 58488 added to language.oop5.autoload | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-98139@lists.php.net to get a copy of this message | ||
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:)
----
Manual Page -- http://www.php.net/manual/en/language.oop5.autoload.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+58488
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+58488&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+58488&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+58488&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+58488&report=yes&reason=useless
Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+58488&report=yes&reason=non-english
Delete: already in docs -- http://master.php.net/manage/user-notes.php?action=delete+58488&report=yes&reason=already+in+docs
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+58488&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+58488&report=yes
Search -- http://master.php.net/manage/user-notes.php