FAQ |
Kalender |
![]() |
#10 | ||
|
|||
Klarade millennium-buggen
|
Jag har testat lite OOP med PHP och autoloader som jag tänkte dela med mig av:
Först min testklass: Kod:
<?php // File: TestAutoloader.php // Author: Conny Westh 2012-09-13 require_once('/lib/autoloader.php'); try { print "Test av autoloader.php\n"; $c1 = new MyClass1(); $c2 = new MyClass2(); } catch (Exception $e) { print $e->getMessage(); } ?> Kod:
<?php class MyClass1 { public static function run() { print "MyClass1 Works just fine...\n"; } } $className = 'MyClass1'; $className::run(); ?> Kod:
<?php class MyClass2 { public static function run() { print "MyClass2 Works just fine...\n"; } } $className = 'MyClass2'; $className::run(); ?> Autoloader-klassen kan man lägga i en underkatalog som lämpligtvid heter LIB: Kod:
<?php // File: autoloader.php // Modified by Conny Westh 2012-09-13 class autoloader { public static $loader; public static function init() { if (self::$loader == NULL) self::$loader = new self(); return self::$loader; } public function __construct() { spl_autoload_register(array($this,'approot')); spl_autoload_register(array($this,'model')); spl_autoload_register(array($this,'helper')); spl_autoload_register(array($this,'controller')); spl_autoload_register(array($this,'library')); } public function approot($class) { set_include_path(get_include_path().PATH_SEPARATOR.'/'); spl_autoload_extensions('.php'); spl_autoload($class); } public function library($class) { set_include_path(get_include_path().PATH_SEPARATOR.'/lib/'); spl_autoload_extensions('.php'); spl_autoload($class); } public function controller($class) { $class = preg_replace('/_controller$/ui','',$class); set_include_path(get_include_path().PATH_SEPARATOR.'/controller/'); spl_autoload_extensions('.php'); spl_autoload($class); } public function model($class) { $class = preg_replace('/_model$/ui','',$class); set_include_path(get_include_path().PATH_SEPARATOR.'/model/'); spl_autoload_extensions('.php'); spl_autoload($class); } public function helper($class) { $class = preg_replace('/_helper$/ui','',$class); set_include_path(get_include_path().PATH_SEPARATOR.'/helper/'); spl_autoload_extensions('.php'); spl_autoload($class); } } //call autoloader::init(); ?> |
||
![]() |
![]() |
|
|