__dir__在PHP Drush脚本中没有返回脚本路径



添加行:

#!/usr/bin/env drush

到使用drush自动运行的PHP脚本的顶部,变量__DIR____FILE__停止返回我的脚本文件名和目录,然后返回drush路径。

是否有另一个变量在drush脚本中应使用以获取脚本路径?

注意:当我删除该行并使用drush scr <myscript>时,__DIR____FILE__返回正确的路径。

[编辑]

在Hasan Bayat的答案中测试以下建议:

我运行以下脚本:

<?php
print('__DIR__ value is: '.__DIR__."n");
print('__FILE__ value is: '.__FILE__."n");
print('SCRIPT_FILENAME is: '.$_SERVER['SCRIPT_FILENAME']."n");
print('PATH_TRANSLATED is: '.$_SERVER['PATH_TRANSLATED']."n");
print('from backtrace: '.debug_backtrace()[count(debug_backtrace()) - 1]['file']."n");
print('included_files: '.get_included_files()[0]."n");

使用命令行:

drush scr script.php

,结果如下

__DIR__ value is: /path/to/my/script
__FILE__ value is: /path/to/my/script/script.php
SCRIPT_FILENAME is: /path/to/current/dir/index.php
PATH_TRANSLATED is: /usr/local/bin/drush
from backtrace: /usr/local/bin/drush
included_files: /usr/local/bin/drush
然后,我更改了脚本以在顶部添加线#!/usr/bin/env drush。这次用命令重新读脚本:
./script.php

现在结果如下:

__DIR__ value is: phar:///usr/local/bin/drush/commands/core
__FILE__ value is: phar:///usr/local/bin/drush/commands/core/core.drush.inc(1194) : eval()'d code
SCRIPT_FILENAME is: /path/to/current/dir/index.php
PATH_TRANSLATED is: /usr/local/bin/drush
from backtrace: /usr/local/bin/drush
included_files: /usr/local/bin/drush

显然,如果将第一行添加到脚本中,则建议的解决方案都不适用。

有几种方法,但这是两个:

  1. 使用$_SERVER全局变量:检查您的$_SERVER["SCRIPT_FILENAME"]已存在并指向当前文件,然后,如果它不起作用,则使用$_SERVER["PATH_TRANSLATED"]可能会有效。
  2. 如果$_SERVER变量无效,请使用以下代码:
$stack = debug_backtrace();
$firstFrame = $stack[count($stack) - 1];
$initialFile = $firstFrame['file'];

如果他们都没有工作使用getcwd();获取当前工作目录并按照您的文件名进行关注。

edit :第三种方法是使用get_included_files(),如果您之前没有任何包含的文件,您的当前文件应为:

$included_files = get_included_files();
echo $included_files[0]; // Outputs current script path

最新更新