【问题标题】:How to make "require"-config file only on specific file when use composer使用作曲家时如何仅在特定文件上制作“require”-config文件
【发布时间】:2019-11-27 05:09:44
【问题描述】:

使用 composer 时如何只在另一个文件上需要配置文件?

考虑在这个文件的根目录中有一个名为“config.php”的文件,我们有一些变量,比如 $site_url :

$config = [
    // e.g (http://example.com or https://exmaple.com)
    "site_url" => "http://localhost"
];

并且在包含文件夹“include/DBConnect.php”中有一个名为“DBConnect”的类,现在我们要使用保存在类“DBConnect”中的config.php上的变量,写好require“../config.php”;并使用变量。

<?php


namespace Admin\includes;
require "../config.php";

class DBConnect
{
    //dsn : engine:Servername;DbName;charset;
    protected $engine;
    protected $servername;
    protected $dbname;
    protected $charset;



    public function __construct()
    {


    }
}
index.php
<?php
require  "vendor/autoload.php";

$tp1 = new \Admin\includes\DBConnect();

现在我们在 index.php 中调用 getname 类,调用它时 php 返回错误

Warning: require(../config.php): failed to open stream....

【问题讨论】:

    标签: php composer-php


    【解决方案1】:

    使用__DIR__魔术常量创建相对于当前目录的路径:

    require __DIR__ . "/../config.php";
    

    【讨论】:

    • 感谢您解决问题的帮助。但是现在没有全局关键字无法访问类中的 config.php 变量,为什么?因为使用命名空间还是有别的原因?
    • 使用全局变量是一种不好的做法。将 config.php 作为库的一部分也是一种不好的做法。最好在 index.php 或控制器代码中要求配置并将 $config 作为参数传递给new \Admin\includes\DbConnect($config);
    猜你喜欢
    • 2017-05-10
    • 2021-03-08
    • 2015-10-14
    • 2013-06-04
    • 2015-07-04
    • 2020-01-31
    • 1970-01-01
    • 2017-09-13
    • 1970-01-01
    相关资源
    最近更新 更多