从目录名 (__FILE__) 向上获取 2 级
如何从当前文件(仅 2 个目录以上)返回路径名?
因此,如果我当前的文件 URL 返回 theme/includes/functions.php
我怎样才能返回“theme/”
当前我正在使用
return dirname(__FILE__)
How can I return the pathname from the current file, only 2 directories up?
So if I my current file URL is returning theme/includes/functions.php
How can I return "theme/"
Currently I am using
return dirname(__FILE__)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
PHP 5.3+
PHP 5.2 及更低版本
对于 PHP7,通过指定
dirname
的第二个参数来进一步向上移动目录树。 7 之前的版本将需要进一步嵌套dirname
。http://php.net/manual/en/function.dirname.php
PHP 5.3+
PHP 5.2 and lower
With PHP7 go further up the directory tree by specifying the 2nd argument to
dirname
. Versions prior to 7 will require further nesting ofdirname
.http://php.net/manual/en/function.dirname.php
比
dirname(dirname(__FILE__));
更简单的是使用 __DIR__从 php 5.3 开始工作。
Even simpler than
dirname(dirname(__FILE__));
is using __DIR__which works from php 5.3 on.
如何将 config.php 包含在 somefile.php 中?您需要使用当前 somefile.php 文件中具有 3 个目录结构的 dirname。
How can you include config.php in somefile.php? You need to use dirname with 3 directories structure from the current somefile.php file.
正如 @geo 所建议的,这是一个增强的目录名函数,它接受具有目录名搜索深度的第二个参数:
注意:@todo 可能是相关的。
唯一的问题是,如果此函数位于外部包含文件中(例如 util.php),则无法使用它来包含此类文件:B
As suggested by @geo, here's an enhanced dirname function that accepts a 2nd param with the depth of a dirname search:
Note: that @todo may be relevant.
The only problem is that if this function is in an external include (e.g. util.php) you can't use it to include such file :B
虽然迟到了,但您也可以执行如下操作,根据需要多次使用
\..\..\
来向上移动目录级别。$credentials = 需要 __DIR__ 。 '\..\App\Database\config\file.php';
相当于:
$credentials = dirname(__DIR__) 。 '\App\Database\config\file.php';
的好处是它避免了必须嵌套目录名,例如:
dirname(dirname(dirname(__DIR__))
请注意,这在 IIS 服务器上进行了测试 - 不确定 Linux 服务器,但我不明白为什么它不起作用。
Late to the party, but you can also do something like below, using
\..\..\
as many times as needed to move up directory levels.$credentials = require __DIR__ . '\..\App\Database\config\file.php';
Which is the equivalent to:
$credentials = dirname(__DIR__) . '\App\Database\config\file.php';
The benefit being is that it avoids having to nest dirname like:
dirname(dirname(dirname(__DIR__))
Note, that this is tested on a IIS server - not sure about a linux server, but I don't see why it wouldn't work.
这是一个老问题,但仍然相关。
使用:
仅返回第二个父文件夹名称 - 在本例中为“主题”。
http://php.net/manual/en/function.basename.php
This is an old question but sill relevant.
Use:
to return just the second parent folder name - "theme" in this case.
http://php.net/manual/en/function.basename.php