【问题标题】:Autoload + Namespace works in localhost, but don't work in serverAutoload + Namespace 在 localhost 中有效,但在服务器中无效
【发布时间】:2016-11-01 22:01:04
【问题描述】:

我有这个代码可以在 localhost 中使用,但在我的服务器中无法使用,我有一个名为 platform 的文件夹,路径是 /var/www/html/platform

平台/.htaccess

AcceptPathInfo On
RewriteEngine on
RewriteBase /var/www/html/platform/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ index.php?request=$1 [L,QSA]

平台/autoload.php

function __autoload($className) {
$file = $className . '.php';
if(file_exists($file)) {
     require_once $file;
}else{
    //fail
}

平台/index.php

include ('autoload.php');

$controller = new application\controllers\Controller();

平台/应用程序/控制器/Controller.php

namespace application\controllers;

class Controller{

}

在我的本地主机中,此代码有效,但在我的服务器中,我收到以下消息:

致命错误:类 'application\controllers\controller' 未在 /var/www/html/platform/index.php 第 12 行

我该如何解决这个问题?我正在使用 Ubuntu PHPMyAdmin on 14.04 (Digital Ocean)

【问题讨论】:

  • 您的自动加载是否符合 PSR-4 标准?此外,您还可以查看 spl_autoloading。
  • @MueyiwaMosesIkomi PSR-4 标准? spl_autoloading?这对我来说是新的……我不明白你在说什么……你有教程或类似的东西吗?
  • 我将发布一个关于我如何处理自动加载的答案,在我实施的任何地方都可以工作
  • 这个怎么样:$file = './'. $className . '.php';
  • @Kazz 不起作用...

标签: php .htaccess ubuntu-14.04 digital-ocean


【解决方案1】:

注册自动装载机。 * * 基于此处找到的官方 PSR-4 自动加载器示例: * https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader-examples.md

这是一个简单的自动加载类,也应该处理命名空间

class Autoload {

    public function __construct(){

    spl_autoload_register(function ($class) {

        // project-specific namespace prefix
        $prefix = 'App\\';

        // For backwards compatibility
        $customBaseDir = '';

        // base directory for the namespace prefix
        $baseDir = $customBaseDir ?: __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
        $relativeClass = 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 = rtrim($baseDir, '/') . '/' . str_replace('\\', '/', $relativeClass) . '.php';

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

保存在 Autoload.php 类中。包括路径和初始化使用.. $autoload = new Autoload;

【讨论】:

    猜你喜欢
    • 2013-01-25
    • 1970-01-01
    • 2020-07-02
    • 1970-01-01
    • 1970-01-01
    • 2021-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多