Studyon Minte9.com
ZCE 5.3

Study

Exceptions & Autoload



	// try/catch; throw new Exception; set_excepton_handler
	// Autoload - referencing a non-existing class PHP use __autoload
	// SPL autoload - mixing diferent libraries
        // Late static binding | static::who() / B not A

An exception that is thrown in try{} block is passed on to catch{} block.

<?php $error = true; try { if ($error) { throw new Exception ("This is my error"); } } catch (Exception $e) { echo $e->getMessage(); // --- Look Here --- // // output: This is my error }
  Exception class can be extended, to use different nested try/catch blocks.
<?php class myException extends Exception { } try { // ... } catch (myException $e) { // --- Look Here --- // echo $e->getMessage(); } } catch (Exception $e) { echo $e->getMessage(); }
  PHP allows to define a catch-all function that is automatically called.
<?php function handleUncaughtExcetion($e) { echo $e->getMessage(); } set_exception_handler("handleUncaughtExcetion"); throw new Exception ("My error!"); // output: My error! echo "This is never displayed"; // Without exception handler, will have: // --- Look Here --- // // Fatal error: Uncaught exception 'Exception' with message 'My error!'
  Autoload facility allows to load classes on-demand.
<?php function __autoload($class) { // --- Look Here --- // require_once str_replace("_", "/", $class); } $obj = new Article_Model();
  The Standard PHP Library (SPL) offer a solution when working with different classes and libraries.
<?php //Register an autoload function function myAutoLoader($className) { include("classes/$className.php"); } spl_autoload_register("myAutoLoader"); // --- Look Here --- // //Register another autoload function function myOtherAutoLoader($className) { include("include/$className.php"); } spl_autoload_register("myOtherAutoLoader"); // --- Look Here --- // $obj = new MyClass1(); $obj2 = new MyClass2();
  Late static bindings allows you to call a class that was initially called at runtime.
<?php class A { public static function who() { echo __CLASS__; } public static function test() { self::who(); // Normal static::who(); // Late Static Binding // --- Look Here --- // } } class B extends A { public static function who() { echo __CLASS__; } } B::test(); // Output: A (Normal) // Output: B (LSB) // --- Look Here --- //