How to load classes in PHP ?


In PHP, classes can be loaded using the include or require statements. These statements are used to include a PHP file that contains the class definition.

Here are the steps to load a class in PHP:

  • Create a PHP file that contains the class definition. For example, let's create a file named MyClass.php that contains the following code:
class MyClass {
    public function sayHello() {
        echo "Hello World!";
    }
}
  • In your PHP script, use the include or require statement to load the class file. For example:
require 'MyClass.php';
  • Once the class file is loaded, you can create an instance of the class and call its methods. For example:
$obj = new MyClass();
$obj->sayHello(); // Output: Hello World!

Alternatively, you can use PHP's autoloading feature to automatically load classes as they are needed. This can be done by defining an autoloader function that maps class names to file paths. Here's an example:

spl_autoload_register(function ($class_name) {
    include $class_name . '.php';
});

$obj = new MyClass();
$obj->sayHello(); // Output: Hello World!

In this example, the spl_autoload_register function registers an anonymous function as an autoloader. This function takes a class name as its parameter and includes the corresponding PHP file. When the new MyClass() statement is executed, PHP automatically calls the autoloader function to load the MyClass class.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.