note 103571 deleted from language.oop5.autoload by danbrown

From: Date: Wed, 20 Apr 2011 18:35:02 +0000
Subject: note 103571 deleted from language.oop5.autoload by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-179024@lists.php.net to get a copy of this message
Note Submitter: Spiro Andreakis ---- Here's an autoload function that works both for normal classes as well as for namespaces. Is there an easier way to do this for namespaces? set_include_path might do the job but it didn't worked for me so I'll keep using my solution :D general.php: <?php /** * YES value * @var int */ define('YES',1); //A 'YES' or 'NO' is doc friendly /** * NO value * @var int */ define('NO',0); /** * Define wether SMARTY template engine is active * @var int */ define('SMARTY_ENABLED',NO); //I use Smarty for some developments so I'll leave it here /** * Define classes directory location * @var string */ define('PHP_CLASSES_PATH','C:/Program Files/Zend/Apache2/htdocs/project/php/classes'); // Set it to whatever path you like /** * Define namespaces location * @var string */ define('PHP_NAMESPACES_PATH',PHP_CLASSES_PATH); //Same as PHP_CLASSES_PATH, set this to whatever path you like, it's just an example ;) /** * If SMARTY is enabled the define the proper path */ if(SMARTY_ENABLED===YES){ define('SMARTY_DIR','C:/Program Files/Zend/Apache2/htdocs/project/Smarty/libs'); } /** * Autoload function for classes * Needs following constants to be set: SMARTY_ENABLED,YES,SMARTY_DIR, PHP_NAMESPACES_PATH and PHP_CLASSES_PATH * @param $class Class name, it is set automatically * @throws Exception */ function __autoload($class){ $class = strtolower($class); //I assume all filenames are in lowercase, class name can be ProjectConfig and the autoload function will look for the file projectconfig if($class == 'smarty'){ if(SMARTY_ENABLED === YES){ require_once (SMARTY_DIR . DIRECTORY_SEPARATOR . "Smarty.class.php"); } else{ throw new Exception('SMARTY is not enabled'); } } else{ if(strpos('\\',$class)){ $class = preg_replace('/\\/',DIRECTORY_SEPARATOR,$class); //Sometimes the OS will not recognize namespaces separator as a directory separator require_once (PHP_NAMESPACES_PATH . DIRECTORY_SEPARATOR . $class . ".php"); } else{ require_once (PHP_CLASSES_PATH . DIRECTORY_SEPARATOR . $class . ".php"); } } } ?> file.php: <?php require_once('./general.php'); use Something/Client; //Change '/' for '\' $client = new Client(); $client2 = new Something/Client(); //Change '/' for '\' ?>

« previous php.notes (#179024) next »