note 107174 added to language.oop5.autoload
| From: | shaftouille at osu1 dot php dot net | Date: | Thu, 12 Jan 2012 09:14:42 +0000 |
| Subject: | note 107174 added to language.oop5.autoload | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-185598@lists.php.net to get a copy of this message | ||
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";
}
}
----
Server IP: 69.147.83.197
Probable Submitter: 87.231.159.28
----
Manual Page -- http://www.php.net/manual/en/language.oop5.autoload.php
Edit -- https://master.php.net/note/edit/107174
Del: integrated -- https://master.php.net/note/delete/107174/integrated
Del: useless -- https://master.php.net/note/delete/107174/useless
Del: bad code -- https://master.php.net/note/delete/107174/bad+code
Del: spam -- https://master.php.net/note/delete/107174/spam
Del: non-english -- https://master.php.net/note/delete/107174/non-english
Del: in docs -- https://master.php.net/note/delete/107174/in+docs
Del: other reasons-- https://master.php.net/note/delete/107174
Reject -- https://master.php.net/note/reject/107174
Search -- https://master.php.net/manage/user-notes.php