I’m trying to figure out how to exactly autoload classes in PHP. It seems like I keep running into having to write really long class names when creating new objects. This is kind of annoying depending on the folder structure.
define('APPLICATION_PATH', realpath('.'));
function __autoload($class_name)
{
$path = APPLICATION_PATH . DIRECTORY_SEPARATOR . "lib" . DIRECTORY_SEPARATOR . $class_name . ".php";
if (file_exists($path))
require_once $path;
}
$customer = new AppName\Models\Customer();
echo $customer->GetName();
$cr = new AppName\Repository\CustomerRepository();
echo $cr->GetName();
I know I can use a use statement to shorten it, but then I’d have to write a bunch of use statements.
Is there a better way of doing this? Or maybe something I am missing to make it easier?
No, You have either write the full name of the class or write the use statements.