Tags
Asked 3 years ago
10 Jun 2021
Views 497
Norberto

Norberto posted

Autoload module class in Prestashop

Autoload module class in Prestashop
Rasi

Rasi
answered Apr 27 '23 00:00

In PrestaShop, you can use the autoload feature to load a module class automatically. To do this, you need to follow these steps:

Create a PHP file with the same name as your module in the root directory of your module. For example, if your module is named "my_module", create a file named "my_module.php".

Define a class with the same name as your module in the PHP file. For example, if your module is named "my_module", define a class named "my_module".

Use the __autoload() function to load the class automatically. This function is called whenever a class is not found in the current script. Here's an example:



function __autoload($classname) {
    if (strpos($classname, 'my_module') !== false) {
        include(_PS_MODULE_DIR_.'my_module/'.$classname.'.php');
    }
}

In this example, the __autoload() function checks if the class name contains the string "my_module". If it does, it includes the PHP file that defines the class.

Save the PHP file and upload it to the root directory of your module.
With these steps, your module class will be loaded automatically when it is needed. Note that you can customize the autoload function to load multiple classes or to use a different naming convention for your module files.
Post Answer