note 89515 added to language.oop5.autoload
| From: | claude dot pache at gmail dot com | Date: | Thu, 12 Mar 2009 03:04:55 +0000 |
| Subject: | note 89515 added to language.oop5.autoload | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-151753@lists.php.net to get a copy of this message | ||
About static classes that need initialisation before use (problem discussed by adam at
greatbigmassive dot net and kalkamar at web dot de below).
Simple problems have often simple solutions. Here is my approach:
First, my __autoload function is very simple:
<?php
function __autoload ($class_name)
{
if (preg_match('|^\w+$|', $class_name))
include "./packages/$class_name.php";
}
?>
(The "if/preg_match" line is just a simple yet robust security check. Moreover I use
"include" and not "require"/"require_once", so that if the file is not
found, the __autoload function does nothing, and my script dies eventually with a meaningful
"Class 'foo' not found" fatal error.)
Now, when I define a class "foo" which requires initialisation before use, I just write
the initialisation code after the definition of the class in the file "packages/foo.php":
<?php
/** Content of file "packages/foo.php" **/
class foo
{
/* definition of the class is found here */
}
/* initialisation code of the class is found here. */
/** End of file "packages/foo.php" **/
?>
That's it. No need for an <? init() ?> or a <? __construct() ?> method.
----
Server IP: 89.31.146.176
Probable Submitter: 83.181.100.209
----
Manual Page -- http://www.php.net/manual/en/language.oop5.autoload.php
Edit -- https://master.php.net/note/edit/89515
Del: integrated -- https://master.php.net/note/delete/89515/integrated
Del: useless -- https://master.php.net/note/delete/89515/useless
Del: bad code -- https://master.php.net/note/delete/89515/bad+code
Del: spam -- https://master.php.net/note/delete/89515/spam
Del: non-english -- https://master.php.net/note/delete/89515/non-english
Del: in docs -- https://master.php.net/note/delete/89515/in+docs
Del: other reasons-- https://master.php.net/note/delete/89515
Reject -- https://master.php.net/note/reject/89515
Search -- https://master.php.net/manage/user-notes.php