=================== Classes and Objects =================== ------------------------------ Loading Classes and Interfaces ------------------------------ In normal PHP, you would load a class or interface file using include or require. {{code: php require_once "My/Example/Class.php"; }} However, if `My/Example/Class.php` did not have the My_Example_Class in it for some reason, PHP does not care. If you try to instantiate `My_Example_Class` the definition is not available, and PHP will throw an error; this can be a difficult error to track down. The [[Solar::autoload()]] method is the equivalent of include/require, but adds a [[php::class_exists() | ]] check to see if the class was actually loaded from the file. It won't attempt to load the same class more than once. {{code: php Solar::autoload('My_Example_Class'); }} If the 'My_Example_Class' still does not exist after calling [[Solar::autoload()]], Solar throws an exception with a backtrace to let you know the load failed and where it was called from. This makes it easy to track down failed class loads. For the autoload method to work, the class or interface to be loaded must be in the same directory as the Solar directory (typically the PEAR library path) and conform to the [class naming conventions][]. Note that when using [[Solar::factory()]], you **do not** need to use [[Solar::autoload()]] first; [[Solar::factory()]] automatically calls [[Solar::autoload()]] to load the requested class file. Also note that [[Solar::autoload()]] is registered with [[php::spl_autoload_register() | ]] by the Solar.php file, so you don't even have to load classes at definition time if you don't want to. ===================== Instantiating Objects ===================== In normal PHP, you must include a class file and then instantiate it. {{code: php // normal use require_once 'My/Example/Class.php'; $obj = new My_Example_Class(); }} With Solar, if you want to instantiate a new object, you can use the [[Solar::factory()]] method instead of the include-and-instantiate routine. {{code: php // Solar object factory $obj = Solar::factory('My_Example_Class'); }} This method uses [[Solar::autoload()]] internally to load the class file. If the class conforms to the Solar standards for [constructor parameters][], the class will be configured automatically with its corresponding values from the [[config file]]. If you want to override those values, you can pass a custom config array as the second parameter: {{code: php $options = array('zim' => 'gir', 'baz' => 'dib'); $obj = Solar::factory('My_Class_File', $options); }} For this method to work, the class to be loaded must be in the include_path and conform to the [class naming conventions][]. [class naming conventions]: /manual/Project_standards/Naming_conventions [constructor parameters]: /manual/Project_standards/Constructor_parameters