包括类中的相对路径变化(奇怪的行为)

我不想使用自动加载!


我有一个get_class包含与当前类相关的文件的方法的类


我在类中多次调用该方法(始终是类的相同实例),但有时当前类的相对路径不起作用/更改?


看起来很奇怪..如果我把工作目录(CWD)的相对路径像'php/map/app/'.$type.'/'.$name.'.php'它一样总是有效


什么可能导致这种情况?


该方法是从类的同一个实例和同一个 PHP 进程/请求调用的,所以看起来很奇怪,相对路径有时才有效(它会改变)


脚本总是从同一个来源执行 /some-dir/inde.php


private function get_class(string $type, string $name): string{

    $name = ucfirst($name);

    $file = 'map/app/'.$type.'/'.$name.'.php';


    if(!include_once $file){

        throw new Error('File missing: '.$file);

    }


    return '\\dbdata\\'.$type.'\\'.$name;

}


烙印99
浏览 169回答 3
3回答

蛊毒传说

考虑到相对路径,它似乎is_file()并且include_once()不是以相同的方式“工作”。一切都按预期工作。我正在测试is_file()

宝慕林4294392

如果您从与包含文件所在的文件夹不同的文件夹中执行此脚本,它将失败。根据根路径查找文件(在开头添加 /)或使用某种自动加载器。这可以由 Composer 轻松管理,您的 composer.json 文件将如下所示:"autoload": {    "psr-4": {        "dbdata\\": "map/app/"    },    "classmap": [        "any/additional/classes/to/map"    ]}您需要确保您的 php 文件是命名空间的。然后您还必须vendor/autoload.php在访问任何映射类之前包括

墨色风雨

您需要阅读:1)Php 命名空间 2)Php 自动加载类 3)使用命名空间导入类简单示例(类文件夹/classes/autoload.php):spl_autoload_register(function($class) {&nbsp; &nbsp; // convert namespace to full file path&nbsp; &nbsp; $class = 'classes/' . str_replace('\\', '/', $class) . '.php';&nbsp; &nbsp; // Load class if exists&nbsp; &nbsp; if (file_exists($class)) {&nbsp; &nbsp; &nbsp; &nbsp; if (!class_exists($class)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; require_once($class);&nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }});类示例(classes/Auth/Login/Auth.php):<?php// Create namespacenamespace Auth\Login;// import other class if neededuse Auth\Login\Mysql;// class sample with or without extendsclass Auth extends Mysql{&nbsp; &nbsp; &nbsp;... class methods here ...}?>然后从命名空间(router.php)加载类:<?phprequire_once($_SERVER['DOCUMENT_ROOT'].'/classes/autoload.php');// Load class&nbsp;use Auth\Login\Auth;try{&nbsp; &nbsp; $r = new Auth();}catch(Exception $e){&nbsp; &nbsp; echo '<h4 style="color: #222; font-size: 15px; font-family: Arial">'.$e->getMessage().'<h4>';}?>或者只是从完整路径加载:require_once($_SERVER['DOCUMENT_ROOT'].'/path-to-class/ClassName.php');&nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP