php i autoload
marzec 19, 2008 autor rofrol
Możemy sprawdzać czy przed ładowaniem czy istnieje już w pamięci klasa, wtedy nie ładujemy pliku.
class_exists('myClass') || require('path/to/myClass.class.php');
Możemy także zdefiniować magiczną funkcję __autoload. Pliki zawierające definicję klasy, będą ładowane podczas tworzenia obiektu danej klasy.
Jaki plik załadować określamy w klasie __autoload:
function __autoload($filename) {
require_once "{$filename}.php";
}
$myobject = new myobject();
A co jeśli w innym pliku załadowanym będzie inna definicja funkcji __autoload? Nadpisze to naszą własną definicję. Możemy wtedy użyć sp1_autoload_register()
// Our autoload functions
function my_autoload1_function($filename) {
@require_once "{$filename}-example1.php";
}
function my_otherautoload1_function($classname) {
@require_once "{$classname}-example2.php";
}
// Register them using sp1_autoload_register()
// Pass the function names to this function and it will register the functions.
sp1_autoload_register('my_autoload1_function');
sp1_autoload_register('my_otherautoload1_function');
$myobject = new myobject();
Tylko, że użycie sp1_autoload_register() usuwa wcześniejsze definicje __autoload. Zatem przed użuciem sp1_autoload_register() dodajmy poprzednie definicje do rejestru a potem nasze.
// Check to see if we already have an __autoload defined, and if so, register it.
if (function_exists('__autoload')) {
sp1_autoload_register('__autoload');
}
// Register the other functions.
sp1_autoload_register('my_autoload1_function');
sp1_autoload_register('my_otherautoload1_function');
Napisz odpowiedź
Musisz być zalogowany żeby dodać komentarz.