如何在php代码中调用__autoload()

时间:2012-10-03 05:46:20

标签: php autoload autoloader

我是php新手,我想在我的代码中使用php5的__autoload功能。我在index.php中编写了下面的代码,但我不明白我应该如何以及何时调用__autoload函数。

function __autoload($class) {
    if (file_exists($class . '.php')) {
        include($class . '.php');
    } else {
        throw new Exception('Unable to load class named $class');
    }
}

我也见过this thread,但我的应用程序中没有这样的自动加载器类。每个应用程序是否需要单独的类才能使用自动加载?如果没有,我可以像上面这样的单一功能完成它的任务吗? 任何人都可以解释如何在我的PHP代码中调用上面的__autoload函数?

5 个答案:

答案 0 :(得分:13)

你不是自己调用__autoload(),PHP在尝试查找类的实现时会这样做。

例如......

function __autoload($className) {
     include $className . '.php';
}

$customClass = new CustomClass;

...这将调用__autoload(),将CustomClass作为参数传递。这个(例如愚蠢的)__autoload()实现将尝试通过在最后添加php扩展名来包含文件。

另外,您应该使用spl_autoload_register()代替。然后,您可以使用多个实现,在使用带有自动加载器的多个库时非常有用。

  

...不鼓励使用__autoload(),将来可能会弃用或删除。

Source

答案 1 :(得分:6)

在PHP中__autoload()是一个神奇的方法,意味着当你尝试创建类的对象时它会自动调用,如果PHP引擎在脚本中找不到类,它将尝试调用__autoload()魔法方法

您可以按照以下示例实现它:

function __autoload($ClassName)
{
    include($ClassName.".php");
}

$CustomClassObj = new CustomClass();
$CustomClassObj1 = new CustomClass1();
$CustomClassObj2 = new CustomClass2();

创建新对象时,它会自动包含所有类文件。

P.S。为此,您必须提供与类名相同的类文件名。

答案 2 :(得分:2)

你们需要使用require_once而不是include来消耗你的记忆 最好的方法是:

function __autoload($class) {
   $class_name = strtolower($class);
   $path       = "{$class}.php";
   if (file_exists($path)) {
       require_once($path);
   } else {
       die("The file {$class}.php could not be found!");
   }
}

答案 3 :(得分:0)

不要使用__autoload()而是使用spl_autoload_register。 See php manual

spl_autoload_register()为自动加载类提供了更灵活的替代方法。因此,不鼓励使用__autoload(),将来可能会弃用或删除。

    <?php

    // function __autoload($class) {
    //     include 'classes/' . $class . '.class.php';
    // }

    function my_autoloader($class) {
        include 'classes/' . $class . '.class.php';
    }

    spl_autoload_register('my_autoloader');

    // Or, using an anonymous function as of PHP 5.3.0
    spl_autoload_register(function ($class) {
        include 'classes/' . $class . '.class.php';
    });

    ?>

答案 4 :(得分:0)

您还可以使用#include <iostream> #include <chrono> #include <thread> #include <unistd.h> #include <signal.h> using namespace std; pid_t display_image_file (const char *image_file) { pid_t pid = fork (); if (pid == -1) { std::cout << "Could not fork, error: " << errno << "\n"; return -1; } if (pid != 0) // parent return pid; // child execlp ("feh", "-F", image_file, NULL); // only returns on failure std::cout << "Couldn't exec feh for image file " << image_file << ", error: " << errno << "\n"; return -1; } int main() { pid_t pid = display_image_file ("nav.png"); if (pid != -1) { std::this_thread::sleep_for (std::chrono::milliseconds (2000)); kill (pid, SIGKILL); } pid_t pid2 = display_image_file ("sms2.png"); } 来加载php文件,这比 以spl_autoload_register()为例:

__autoload