【问题标题】:require_once can't load existing file on Windows 10 (works on Linux)require_once 无法在 Windows 10 上加载现有文件(适用于 Linux)
【发布时间】:2017-02-21 16:51:25
【问题描述】:

我们的自动加载器有一个神秘的问题:

function psr4_default_autoload( $class )
{
    // project-specific namespace prefix
    $prefix = 'basefolder\\';

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

    // 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 ( file_exists( $file ) ) {
        require_once $file;
    }
}

SOURCE_DIR是绝对路径。否则它是原始的 psr4 自动加载器示例:https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader-examples.md

此自动加载器可在我的 Linux PC 和我们的服务器上运行。但是,在 Windows 上 file_exists( $file ) 返回 true,但 require_once $file; 将不起作用。如果我们回显$file,它会准确地返回我们要加载的文件,并且该文件也准确地存在于那里。

错误信息是:

致命错误:在第 14 行的 C:\xampp\htdocs\xyz\classes\DatabaseAbstraction\Entity\UserLogin.php 中找不到类 'basedir\DatabaseAbstraction\AEntity'

那行是:class UserLogin extends AEntity。背景:

namespace basedir\DatabaseAbstraction\Entity;


use basedir\DatabaseAbstraction\AEntity;

class UserLogin extends AEntity

有什么想法吗?

【问题讨论】:

  • 现在我会保留我的答案,因为我相信无论如何您都会遇到这个问题...关于您的编辑,触发错误时$file 的内容是什么?跨度>
  • $file 一切正常。 <?php 中缺少一个 php ...
  • 至少你现在有一些工作。不过,为此添加检查可能会很好;)

标签: php windows psr-4


【解决方案1】:

Windows 目录分隔符是“\”,而 Linux 是“/”;您应该使用“DIRECTORY_SEPARATOR”关键字来表示用于创建路径的字符。它是在运行时确定的,具体取决于当前的操作系统。

在你的情况下会给出:

$base_dir = SOURCE_DIR . DIRECTORY_SEPARATOR;
[...]
$file = $base_dir . str_replace( '\\', DIRECTORY_SEPARATOR, $relative_class ) . '.php'; // assuming your $base_dir follows the same logic

您还必须相应地修改 SOURCE_DIR。

【讨论】:

  • 谢谢,但这并没有解决问题。我编辑了我的问题。自动加载器适用于一个类,但不适用于它扩展的类。
  • @Jaime:哪个 Windows 版本?哪个PHP版本?我会对此感兴趣:)
【解决方案2】:

仅作记录:

文件 AEntity.php 以 <? 而不是 <?php 开头。这就是该文件没有加载到该 Windows 计算机上的原因。

我现在要哭了。

【讨论】:

  • 短标签是 php.ini 中的一个配置选项。可能两台电脑的设置不同。无论设置如何,我建议始终使用<?php
猜你喜欢
  • 1970-01-01
  • 2011-03-09
  • 2018-04-17
  • 2019-01-27
  • 1970-01-01
  • 2015-09-06
  • 1970-01-01
  • 1970-01-01
  • 2015-03-11
相关资源
最近更新 更多