【问题标题】:How to autoload and call an independent PHP class without using require_once?如何在不使用 require_once 的情况下自动加载和调用独立的 PHP 类?
【发布时间】:2019-09-19 11:49:36
【问题描述】:

我有一个主类叫EQ,连接到其他类,可以在这个GitHub link查看。

EQ 类没有连接到我的composer,我在本地服务器中调用它:

php -f path/to/EQ.php 

和使用 CRON 作业的实时服务器:

1,15,30,45  *   *   *   *   (sleep 12; /usr/bin/php -q /path/to/EQ.php >/dev/null 2>&1)

我不确定如何正确使用自动加载器并将所有依赖文件加载到此类,并删除require_onces。我已经尝试过了,它似乎确实有效:

spl_autoload_register(array('EQ', 'autoload'));

我该如何解决这个问题?

尝试

//Creates a JSON for all equities // iextrading API
require_once __DIR__ . "/EquityRecords.php";
// Gets data from sectors  // iextrading API
require_once __DIR__ . "/SectorMovers.php";
// Basic Statistical Methods
require_once __DIR__ . "/ST.php";
// HTML view PHP
require_once __DIR__ . "/BuildHTMLstringForEQ.php";
// Chart calculations
require_once __DIR__ . "/ChartEQ.php";
// Helper methods
require_once __DIR__ . "/HelperEQ.php";

if (EQ::isLocalServer()) {
    error_reporting(E_ALL);
} else {
    error_reporting(0);
}

/**
 * This is the main method of this class.
 * Collects/Processes/Writes on ~8K-10K MD files (meta tags and HTML) for equities extracted from API 1 at iextrading
 * Updates all equities files in the front symbol directory at $dir
 */

EQ::getEquilibriums(new EQ());

/**
 * This is a key class for processing all equities including two other classes
 * Stock
 */
class EQ
{



}

spl_autoload_register(array('EQ', 'autoload'));

【问题讨论】:

  • 你应该read the manual about auto loading,它有几个例子。您也可以在 "php psr-4 autoloader" 上搜索。或者你可以简单地让 composer 自动加载你的类。
  • 您说spl_autoload_register(array('EQ', 'autoload'));“似乎工作正常”,那么问题出在哪里?
  • 只需将逻辑放入自动加载函数中,以将类名映射到文件位置。当您的代码调用new Something 时,它将类名作为字符串Something 传递;你必须弄清楚它在哪里,然后包含(或要求)它。
  • 不确定您是否说明了问题,但如果需要,请检查php.net/manual/en/function.set-include-path.php

标签: php composer-php autoload autoloader spl-autoload-register


【解决方案1】:

本质上,您的自动加载器函数将类名映射到文件名。例如:

class EQ
{
    public function autoloader($classname)
    {
        $filename = __DIR__ . "/includes/$classname.class.php";
        if (file_exists($filename)) {
            require_once $filename;
        } else {
            throw new Exception(sprintf("File %s not found!", $filename));
        }
    }
}

spl_autoload_register(["EQ", "autoloader"]);

$st = new ST;
// ST.php should be loaded automatically
$st->doStuff();

但是,这些东西大部分都内置在 PHP 中,让您的代码更加简单:

spl_autoload_extensions(".php");
spl_autoload_register();
$st = new ST;
$st->doStuff();

只要ST.php 在您的include_path 中的任何位置,它就可以工作。无需自动加载功能。

【讨论】:

    猜你喜欢
    • 2013-10-29
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-04
    • 1970-01-01
    相关资源
    最近更新 更多