note 70898 deleted from language.oop5.autoload by cmb
| From: | cmb@php.net | Date: | Sun, 29 Dec 2019 10:17:31 +0000 |
| Subject: | note 70898 deleted from language.oop5.autoload by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-213668@lists.php.net to get a copy of this message | ||
Note Submitter: andrew dot delete dot cornes at gmail dot delete dot com
----
If you'd like '__autoload()' to support multiple class folders, each containing
multiple class files (one per class), you may want to try something like this (file
'__autoload.php'):
<?php
define('CLASS_FILENAME_SUFFIX', '.class.php');
function __autoload($className)
{
$__autoloadAbsolutePath = dirname(__FILE__);
// 'pathStart' is your web application root folder.
// (This may or may not be where '__autoload.php'
// resides; let's assume here that it resides one
// level 'below' the web app root.)
$pathStart = $__autoloadAbsolutePath .
DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR;
// 'classPath' is a list of class folders to look in.
// (In this example, there's just one: 'classlibs/lib1'.
// To add more, simply append them; start with
// 'PATH_SEPARATOR . $pathStart .', and off you go...)
$classPath = PATH_SEPARATOR . $pathStart .
'classlibs' . DIRECTORY_SEPARATOR . 'lib1';
// Add list of class folders to 'include_path' for the
// forthcoming 'require()' (or similar directive).
$oldIncludePath = get_include_path();
set_include_path($oldIncludePath . $classPath);
require_once($className . CLASS_FILENAME_SUFFIX);
// Reinstate initial 'include_path'.
set_include_path($oldIncludePath);
}
?>
As your web application develops, new paths containing class files can be added into the
'$classPath' variable within '__autoload()'. If hard-coding the
'$classPath' variable isn't to your taste, you could arrange for its value to come
from 'outside' in whatever way you like.
Any comments gratefully received.