How to Load Classes Dynamically in PHP

How to Load Classes Dynamically in PHP thumbnail
Use PHP to modify the contents of an HTML document.

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.

Things You'll Need

  • PHP editor or text editor
Show More

Instructions

  1. 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.

Tips & Warnings

  • Save classes in the same directory so that they're easy to find.

Related Searches:

References

  • Photo Credit Comstock/Comstock/Getty Images

Comments

Related Ads

Featured