简体   繁体   English

PHP require_once没有得到变量

[英]PHP require_once not getting a variable

I'm trying to get a require_once to work, so I can use a variable content from my bootstrap file. 我试图让require_once工作,所以我可以使用我的bootstrap文件中的变量内容。 I currently have the following file structure: 我目前有以下文件结构:

(folder) lib (文件夹)lib

(folder) templates (文件夹)模板

(file) bootstrap.php (文件)bootstrap.php

On my bootstrap.php file I have the following array: 在我的bootstrap.php文件中,我有以下数组:

$config = array(
"db" => array(
    "db" => array(
        "dbname" => "name",
        "username" => "user",
        "password" => "pass",
        "host" => "localhost"
    ),
),
"paths" => array(
    "resources" => "/src",
)
);

On my lib folder I have the following 2 files: 在我的lib文件夹中,我有以下2个文件:

Database.php User.php Database.php User.php

Both of these are classes. 这两个都是课程。 In my User.php file I want to make use of the array defined in the bootstrap.php file, so I'm doing 在我的User.php文件中,我想使用bootstrap.php文件中定义的数组,所以我正在做

require_once __DIR__ . '/../bootstrap.php';

where DIR is the current folder, and then down a level to where boostrap.php is located. 其中DIR是当前文件夹,然后是一个级别到boostrap.php所在的位置。 But when I make the folowing call: 但是,当我拨打以下电话时:

var_dump( $config );

I get: 我明白了:

Notice: Undefined variable: config in ...\src\lib\User.php on line 37
NULL 

Any idea on what I'm doing wrong? 关于我做错了什么的任何想法?

Use include(file.php); 使用include(file.php); or include_once(file.php); include_once(file.php); instead. 代替。

not sure but try this. 不确定,但试试这个。 EDITED EDITED

require_once('./../bootstrap.php');

or 要么

require('./../bootstrap.php');

instead of this 而不是这个

require_once __DIR__ . '/../bootstrap.php';

I don't know the behaviour on UNIX systems but on Windows DIR outputs something line C:\\Apache24\\htdocs. 我不知道UNIX系统上的行为,但在Windows DIR输出行C:\\ Apache24 \\ htdocs。 Notice the back slashes there. 注意那里的反斜杠。 That s not gonna work with file names unless you use DIR . 除非你使用DIR,否则不能使用文件名。 "..\\libs\\User.php" “.. \\库\\ user.php的”

The arguments for require and require_once are relative to the script file being invoked by your php runtime. require和require_once的参数是相对于php运行时调用的脚本文件。 So if User.php is being required elsewhere (by your root index.php for example) the path being supplied to your require statement needs to be relative to index.php, regardless of which file your require statement is in. 因此,如果在别处需要User.php(例如,通过root index.php),则无论require语句位于哪个文件中,提供给require语句的路径都需要相对于index.php。

If you look at how php frameworks deal with this problem, they typically setup some global APP_PATH variable in the bootstrap sequence (which is an absolute path to the project on disk). 如果你看一下php框架如何处理这个问题,他们通常会在bootstrap序列中设置一些全局的APP_PATH变量(这是磁盘上项目的绝对路径)。

That way, wherever you need to require something, you would base the path off of APP_PATH. 这样,无论您需要什么东西,都可以将路径基于APP_PATH。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM