动态寻找路径,有没有更好的方法? [英] Dynamically finding paths, is there a better way?

查看:51
本文介绍了动态寻找路径,有没有更好的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够移动我的代码并能够发现路径以影响某些变量的值.这将被放置在变量被初始化的页面中.

I want to be able to move my code around and be able to discover the path in order to affect the value of certain variables. This will be placed in the page where the variables get initialized.

这是我想出的:

$path_array = explode('/', $_SERVER['SCRIPT_FILENAME']);

$out = "";
// -3 represents the number of folders and files to go back to reach the wanted path

for($i=0; $i < count($path_array) - 3; $i++){
    $out .= $path_array[$i].'/';
}

然后,例如,我可以执行以下操作:

Then, as an example, I can do the following:

$dyn_path_1 = $out . 'folder1/';
$dyn_path_2 = $out . 'folder2/something_else/';
$dyn_path_3 = $out . 'folder3/';

是否有我可能遗漏的内置函数会使它过时?

Are there built in functions that I could be missing that would make this obsolete?

ps:这将使我们能够拥有多个代码的工作副本,而无需在检查代码时担心这些变量.

ps: this would enable us to have multiple working copies of code without having to worry about these variables whenever we checkout the code.

编辑 #1:

变量文件路径:root/folderA/folderB/var.php

Path of variable file: root/folderA/folderB/var.php

在 var.php 中,我必须返回到根目录,这取决于方法的 2-3 个步骤.我想知道是否有可能做这样的事情:

Within var.php, I have to go back down to root which is 2-3 steps depending on the method. I wonder if it would be possible doing something like this:

echo some_function("../../file_I_know.php");

哪个可以返回:C:/root/

Which could return: C:/root/

推荐答案

看看 PHP 的魔法常量"定义,大多数人使用 dirname(FILE) 来获取目录在最初执行的脚本中,将其绑定到一个常量并将其用作所有其他目录引用的基础.从而使您的脚本位置独立.

Take a look at the "magic constants" definitions for PHP, most people use dirname(FILE) in order to get the directory of the initially executing script, bind that to a constant and use that as the base for all other directory references. Thus making your script position independent.

这是我通常使用的:

if (!defined('SITE_BASE_PATH')) {
  $baseDir = dirname(__FILE__); // Get directory of THIS file
  $baseDir = str_replace("\\", "/", $baseDir); // Replace backslashes with forward incase we're in Windows
  $baseDir = realpath($baseDir); // Convert relative path to real path (no '..' etc)
  $baseDir .= "/"; // Add trailing slash - so that we can append filenames directly
  define('SITE_BASE_PATH', $baseDir); // define the constant
}

或简写:

define(SITE_BASE_PATH, realpath(str_replace("\\", "/", dirname(__FILE__))) . '/');

有关详细信息,请参阅以下帮助:http://php.net/manual/en/language.constants.predefined.php

See the following help for more information: http://php.net/manual/en/language.constants.predefined.php

这篇关于动态寻找路径,有没有更好的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆