如何在不使用require_once的情况下自动加载和调用独立的PHP类?

问题描述 投票:1回答:1

我有一个名为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'));

我该如何解决这个问题?

Attempt

//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'));
php composer-php autoload autoloader spl-autoload-register
1个回答
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的任何地方它只是有效。无需自动加载器功能。

© www.soinside.com 2019 - 2024. All rights reserved.