Introduction
Autoloading helps PHP automatically load classes when needed. Avoiding mistakes makes your code work smoothly without manual includes.
<?php spl_autoload_register(function ($class) { include 'classes/' . $class . '.php'; });
<?php spl_autoload_register(function ($class) { include 'src/' . $class . '.php'; });
<?php spl_autoload_register(function ($class) { $file = __DIR__ . '/lib/' . str_replace('\\', '/', $class) . '.php'; if (file_exists($file)) { include $file; } });
<?php // Autoload function spl_autoload_register(function ($class) { include 'classes/' . $class . '.php'; }); // Assume classes/Hello.php exists with class Hello $hello = new Hello(); $hello->say(); // classes/Hello.php content: // <?php // class Hello { // public function say() { // echo "Hello, autoload!\n"; // } // }
spl_autoload_register in PHP?spl_autoload_register to register autoload functions.spl_autoload_register with the function name as a string parameter.spl_autoload_register(function ($class) {
include 'classes/' . $class . '.php';
});
// Assuming file 'classes/Foo.php' exists and defines class Foo
$obj = new Foo();foo.php (lowercase)?spl_autoload_register(function ($class) {
include_once __DIR__ . '/src/' . str_replace('\\\', '/', $class) . '.php';
});
// Trying to instantiate \App\Utils\Helper
$obj = new \App\Utils\Helper();src/ and lib/. Which approach correctly handles this without errors?spl_autoload_register, which are tried in order.Pass the test and this pattern moves unknown