How to Load Classes Dynamically in PHP
PHP classes consist of user-defined variables and functions that can be used while running a PHP program. For example, a user can create a PHP class called "style" and define variables and functions that modify the style of an HTML page. Classes can be called in multiple PHP documents without defining them in each document; simply save classes in separate PHP files and then load them manually or automatically using the "require_once()" or "_autoload()" functions.
Instructions
-
Load Classes Manually
-
1
Save a class in a PHP document using a PHP editor or text editor. Give the PHP file a recognizable name, such as "className.php" or "className.class.php," where "className" is replaced with the name of the class that is saved in the file.
-
2
Open the PHP document to which you wish to add the saved class.
-
-
3
Type "require_once 'filename.php';" in the PHP document, replacing "filename" with the name of the file in which the PHP class is saved. For example, if you named the PHP file containing the class "result," type "require_once 'result.php';".
-
4
Load additional classes using one "require_once()" statement per class.
Load Classes Automatically
-
5
Save a class in a PHP document.
-
6
Open the PHP document to which you wish to add the saved class.
-
7
Type "function _autoload($className) {require_once $className.'.php';}" in the document. This code doesn't need to be modified, and you can use all of the functions and variables from the saved class in the code.
-
1
Tips & Warnings
Save classes in the same directory so that they're easy to find.
References
- Photo Credit Comstock/Comstock/Getty Images