PHP.mk документација

Автоматско вчитување на класи

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

language.oop5.autoload.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека language.oop5.autoload.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
Автоматско вчитување на класи

Референца за `language.oop5.autoload.php` со подобрена типографија и навигација.

language.oop5.autoload.php

Автоматско вчитување на класи

Many developers writing object-oriented applications create one PHP source file per class definition. One of the biggest annoyances is having to write a long list of needed includes at the beginning of each script (one for each class).

На spl_autoload_register() Многу програмери кои пишуваат објектно-ориентирани апликации создаваат една PHP датотека по дефиниција на класа. Една од најголемите досадни работи е потребата да се напише долг список на потребни вклучувања на почетокот на секое скрипт (едно за секоја класа).

функцијата регистрира кој било број на авто-вчитачи, овозможувајќи класи и интерфејси да бидат автоматски вчитани ако моментално не се дефинирани. Со регистрирање на авто-вчитачи, на PHP му се дава последна шанса да ја вчита класата или интерфејсот пред да заврши со грешка.

Безбедност: стандардниот сет на знаци

Секој конструкт сличен на класа може да се вчита на ист начин. Ова вклучува класи, интерфејси, трајти и броеви. __autoload() Пред PHP 8.0.0, беше можно да се користи spl_autoload_register() and __autoload() за автоматско вчитување на класи и интерфејси. Сепак, тоа е помалку флексибилна алтернатива на

Забелешка:

spl_autoload_register() е отпишано од PHP 7.2.0, и отстрането од PHP 8.0.0.

може да се повика повеќе пати за да се регистрираат повеќе авто-вчитачи. Фрлањето исклучок од функција за авто-вчитување, сепак, ќе го прекине тој процес и нема да дозволи да се извршат понатамошни функции за авто-вчитување. Од таа причина, фрлањето исклучоци од функција за авто-вчитување е силно обесхрабрено.

Пример #1 Пример за авто-вчитување MyClass1 and MyClass2 Овој пример се обидува да ги вчита класите MyClass1.php and MyClass2.php respectively.

<?php
spl_autoload_register
(function ($class_name) {
include
$class_name . '.php';
});

$obj = new MyClass1();
$obj2 = new MyClass2();
?>

од датотеките

Пример #2 Пример за друго авто-вчитување ITest.

<?php

spl_autoload_register
(function ($name) {
var_dump($name);
});

class
Foo implements ITest {
}

/*
string(5) "ITest"

Fatal error: Interface 'ITest' not found in ...
*/
?>

Овој пример се обидува да го вчита интерфејсот

» Композер Пример #3 Користење на авто-вчитувачот на Composer vendor/autoload.php генерира

<?php
require __DIR__ . '/vendor/autoload.php';

$uuid = Ramsey\Uuid\Uuid::uuid7();

echo
"Generated new UUID -> ", $uuid->toString(), "\n";
?>

Белешки од корисници 5 белешки

што е поставено да ги вчитува автоматски пакетите што се управувани од Composer. Со вклучување на оваа датотека, тие пакети можат да се користат без никаква дополнителна работа.
пред 17 години
You should not have to use require_once inside the autoloader, as if the class is not found it wouldn't be trying to look for it by using the autoloader. 

Just use require(), which will be better on performance as well as it does not have to check if it is unique.
jarret dot minkler at gmail dot com
пред 9 години
This is my autoloader for my PSR-4 clases. I prefer to use composer's autoloader, but this works for legacy projects that can't use composer.

<?php
/**
 * Simple autoloader, so we don't need Composer just for this.
 */
class Autoloader
{
    public static function register()
    {
        spl_autoload_register(function ($class) {
            $file = str_replace('\\', DIRECTORY_SEPARATOR, $class).'.php';
            if (file_exists($file)) {
                require $file;
                return true;
            }
            return false;
        });
    }
}
Autoloader::register();
str at maphpia dot com
пред 6 години
Autoloading plain functions is not supported by PHP at the time of writing. There is however a simple way to trick the autoloader to do this. The only thing that is needed is that the autoloader finds the searched class (or any other autoloadable piece of code) from the files it goes through and the whole file will be included to the runtime.

Let's say you have a namespaced file for functions you wish to autoload. Simply adding a class of the same name to that file with a single constant property is enough to trigger the autoloader to seek for the file. Autoloading can then be triggered by accessing the constant property.

The constant could be replaced by any static property or method or by default constructor. However, I personally find a constant named 'load' elegant and informative. After all this is a workaround. Another thing to keep in mind is that this introduces an unnecessary class to the runtime. The benefit of this is that there is no need to manually include or require files containing functions by path which in turn makes code maintaining easier. Such behaviour makes it easier to alter the project structure since manual includes need not to be fixed. Only the autoloader needs to be able to locate the moved files which can be automated.

A code file containing functions.
/Some/Namespace/Functions.php
<?php
namespace Some\Namespace;

class Functions { const load = 1; }

function a () {
}

function b () {
}
?>

Triggering autoloading of the file containing functions.
main.php
<?php
\Some\Namespace\Functions::load;

a ();
b ();
?>
Анонимен
пред 16 години
It's worth to mention, if your operating system is case-sensitive you need to name your file with same case as in source code eg. MyClass.php instead of myclass.php
toi]n[enkayt[attaat]gmaal.com
пред 17 години
Because static classes have no constructor I use this to initialize such classes.
The function init will (if available) be called when you first use the class.
The class must not be included before, otherwise the init-function wont be called as autoloading is not used.

<?php
function __autoload($class_name)
{
    require_once(CLASSES_PATH.$class_name.'.cls.php');
    if(method_exists($class_name,'init'))
        call_user_func(array($class_name,'init'));
    return true;
}
?>

I use it for example to establish the mysql-connection on demand.

It is also possilbe do add a destructor by adding this lines to the function:
<?php
if(method_exists($class_name,'destruct'))
    register_shutdown_function(array($class_name,'destruct'));
?>
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.