Domanda

Ho avuto un piccolo problema con caricamento a mia namespace. Come indicato sul manuale PHP qui: http://us.php.net /manual/en/language.namespaces.rules.php si dovrebbe essere in grado di caricare automaticamente le funzioni dello spazio dei nomi con un pieno qualificato nome di esempio \ Colla \ common \ is_email ().

Cosa è che ho una funzione spl_autoload_register (array ($ importazione, "carico")); all'interno del namespace iniziale, ma ogni volta che provo e call \ colla \ common \ is_email () dallo spazio dei nomi iniziali non passerà che la funzione di caricamento automatico, ma quando si utilizzano nuove is_email () (nel contesto di una classe) lo farà. Io non capisco il manuale dice che posso autoLoad da nomi completi ma non posso:.

Ecco il mio codice:

namespace glue;

require_once 'import.php';

use glue\import as import;
use glue\core\router as router;

$import = new import();

spl_autoload_register(array($import, "load"));

/** Works and echos glue\router **/
$router = new router();

/** Don't do nothing **/
$cheese = \glue\common\is_email($email);

Inoltre ho provato questo codice così:

namespace glue;

require_once 'import.php';

use glue\import as import;
use glue\core\router as router;
use glue\common;

$import = new import();

spl_autoload_register(array($import, "load"));

/** Works and echos glue\router **/
$router = new router();

/** Don't do nothing **/
$cheese = common\is_email($email);

e, infine, questo codice:

namespace glue;

require_once 'import.php';

use glue\import as import;
use glue\core\router as router;
use glue\common\is_email as F;

$import = new import();

spl_autoload_register(array($import, "load"));

/** Works and echos glue\router **/
$router = new router();

/** Don't do nothing **/
$cheese = F($email);
È stato utile?

Soluzione

Ecco la risposta giusto.

Ogni namespace ha bisogno di una propria funzione spl_autoload_register ().

Inoltre, spl_autoload_register () sintassi cambiata in 5.3:

spl_autoload_register(__NAMESPACE__ . "\\className::functionName"));

Il seguente dovrebbe funzionare:

namespace glue;

require_once 'import.php';

use glue\import as import;
use glue\core\router as router;

$import = new import();

spl_autoload_register(__NAMESPACE__ . "\\$import::load"));

/** Works and echos glue\router **/
$router = new router();

/** Don't do nothing **/
$cheese = \glue\common\is_email($email);

Ecco alcuni in diretta codice che funziona solo!

in ../ WebPageConsolidator.inc.php:

class WebPageConsolidator
{
    public function __construct() { echo "PHP 5.2 constructor.\n"; }
}

in test.php:

<?php

namespace WebPage;

class MyAutoloader
{
    public static function load($className)
    {
        require '../' . __NAMESPACE__ . $className . '.inc.php';
    }
}

spl_autoload_register(__NAMESPACE__ . "\\MyAutoloader::load");

class Consolidator extends \WebpageConsolidator
{
    public function __construct()
    {
        echo "PHP 5.3 constructor.\n";

        parent::__construct();
    }
}

// Output: 
// PHP 5.3 constructor.
// PHP 5.2 constructor.

Quindi so che funziona.

Altri suggerimenti

Compositore per caricare automaticamente le vostre classi PHP.

Scopri come farlo nel mio recente post sul blog: https://enchanterio.github.io/enterprise-level-php/2017/12/25/the-magic-behind-autoloading-php-files -utilizzando-composer.html

L'equivoco nella questione del PO è probabilmente che le funzioni / metodi sarebbero soggetti a caricamento automatico - che non lo sono. Caricamento automatico viene attivato solo facendo riferimento a classi.

Questo essere detto resta pur sempre il domanda su autoloading classi namespace :

Dal 2017, la corrente PHP-FIG standard per autoloading è PSR-4 che fornisce la seguente codice caricatore automatico per le classi namespace:

<?php
/**
 * An example of a project-specific implementation.
 *
 * After registering this autoload function with SPL, the following line
 * would cause the function to attempt to load the \Foo\Bar\Baz\Qux class
 * from /path/to/project/src/Baz/Qux.php:
 *
 *      new \Foo\Bar\Baz\Qux;
 *
 * @param string $class The fully-qualified class name.
 * @return void
 */
spl_autoload_register(function ($class) {

    // project-specific namespace prefix
    $prefix = 'Foo\\Bar\\';

    // base directory for the namespace prefix
    $base_dir = __DIR__ . '/src/';

    // does the class use the namespace prefix?
    $len = strlen($prefix);
    if (strncmp($prefix, $class, $len) !== 0) {
        // no, move to the next registered autoloader
        return;
    }

    // get the relative class name
    $relative_class = substr($class, $len);

    // replace the namespace prefix with the base directory, replace namespace
    // separators with directory separators in the relative class name, append
    // with .php
    $file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';

    // if the file exists, require it
    if (file_exists($file)) {
        require $file;
    }
});

Il testo specifica integrale è disponibile all'indirizzo PSR-4: Autoloader .

L'esempio di codice sopra (ed un altro per caricare automaticamente da più namespace) sono disponibili all'indirizzo esempio Implementazioni di PSR-4 (o GitHub: fico standard / accettato / PSR-4-autoloader-examples.md ).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top