note 107174 modified in language.oop5.autoload by danbrown

From: Date: Thu, 12 Jan 2012 17:58:00 +0000
Subject: note 107174 modified in language.oop5.autoload by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-185617@lists.php.net to get a copy of this message
I think there shouldn't be tests in an autoload callback function, this callback will trigger because the class you're trying to load is not defined... in any case if your class is not defined, the code must fail. Therefore an autoload function should be like : <?php spl_autoload_register(function($className) { require(str_replace('\\', '/', ltrim($className, '\\')) . '.php'); }); ?> As the "require" function uses the include_path, the folders for the autoinclusion should be added using set_include_path, let's say your index.php is located in a "public" directory and your MVC classes are in "core", the index.php should be : <?php define('ROOT_DIR', realpath(__DIR__ . '/..')); set_include_path(ROOT_DIR . PATH_SEPARATOR . get_include_path()); ?> And of course you want to catch the loading errors, so you can use class_exists : <?php $className = '\core\Controller\Hello\World'; if (!class_exists($className)) { throw new \ErrorException('Class Not Found !'); } else { $object = new $className(); } ?> This code sample will autoload the "World.php" file located in your "core/Controller/Hello" directory, assuming that your class declaration is like : <?php namespace core\Controller\Hello; class World { function __construct() { echo "Helloworld"; } } ?> --was-- 01 P 11PXP6 OBZ I think there shouldn't be tests in an autoload callback function, this callback will trigger because the class you're trying to load is not defined... in any case if your class is not defined, the code must fail. Therefore an autoload function should be like : spl_autoload_register(function($className) { require(str_replace('\\', '/', ltrim($className, '\\')) . '.php'); }); As the "require" function uses the include_path, the folders for the autoinclusion should be added using set_include_path, let's say your index.php is located in a "public" directory and your MVC classes are in "core", the index.php should be : define('ROOT_DIR', realpath(__DIR__ . '/..')); set_include_path(ROOT_DIR . PATH_SEPARATOR . get_include_path()); And of course you want to catch the loading errors, so you can use class_exists : $className = '\core\Controller\Hello\World'; if (!class_exists($className)) { throw new \ErrorException('Class Not Found !'); } else { $object = new $className(); } This code sample will autoload the "World.php" file located in your "core/Controller/Hello" directory, assuming that your class declaration is like : namespace core\Controller\Hello; class World { function __construct() { echo "Helloworld"; } } http://php.net/manual/en/language.oop5.autoload.php

« previous php.notes (#185617) next »