简体   繁体   English

遇到困难

[英]Having trouble getting paths

I am trying to get the path of a directory which contains a PHP script. 我正在尝试获取包含PHP脚本的目录的路径。 Let's name it script.php . 让我们将其命名为script.php It also contains included log.php . 它还包含包含的log.php

script.php: script.php:

include_once __DIR__.'/../lib/log.php';
func();

log.php: log.php:

function func() {
   file_put_contents(__DIR__.'/log', 'Log file successfully created');
}

I execute script.php expecting the log file appear along with script.php but it doesn't happen. 我执行script.php,希望日志文件与script.php一起出现,但不会发生。 What happens instead is log file is being created in lib directory along with log.php file. 相反,将在lib目录中创建日志文件以及log.php文件。
The only workaround I see here is to pass dir path to log.php through the function as an argument like this: 我在这里看到的唯一解决方法是通过函数将dir路径传递给log.php作为这样的参数:

script.php: script.php:

include_once __DIR__.'/../lib/log.php';
func(__DIR__);

log.php: log.php:

function func($arg) {
   file_put_contents($arg.'/log', 'Log file successfully created');
}

Is it actually possible to get path to script.php through log.php without passing any arguments? 实际上有可能通过log.php来获取script.php的路径而不传递任何参数吗?
I just want to include the script, call a function and create new file along with script which contains include. 我只想包括该脚本,调用一个函数并与包含include的脚本一起创建新文件。

No. PHP does not make any metadata available beyond that relating to the file it is currently executing within. 不可以。PHP除了与当前正在其中执行的文件有关的元数据外,不提供任何其他元数据。

What you can do to make your file paths a bit easier to deal with is define a constant in your config or header file that defines the absolute path to the root of your application. 要使文件路径更易于处理, 可以做的是在配置或头文件中定义一个常量,该常量定义了到应用程序根目录的绝对路径。 Eg: 例如:

define('APPROOT', __DIR__);

Or: 要么:

define('APPROOT', __DIR__ . '/../myapp');

Then you can define paths in your app without trying to rely on where a script happens to live, eg: 然后,您可以在应用中定义路径,而无需尝试依赖脚本的运行位置,例如:

$log_file = APPROOT . '/log/foo.log';

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

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