note 89515 deleted from language.oop5.autoload by crell
| From: | crell@php.net | Date: | Mon, 04 Apr 2022 16:15:23 +0000 |
| Subject: | note 89515 deleted from language.oop5.autoload by crell | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-218040@lists.php.net to get a copy of this message | ||
Note Submitter: claude dot pache at gmail dot com
----
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.