标题说明了一切。我只是想知道是否有一个PHP函数可以告诉我在哪个文件和哪一行设置我的变量
使用PHP魔术常量
__FILE__ -- The full path and filename of the file. If used inside an include, the name of the included file is returned. Since PHP 4.0.2, __FILE__ always contains an absolute path with symlinks resolved whereas in older versions it contained relative path under some circumstances.
__LINE__ -- The current line number of the file.
链接在这里
享受:)
我不这么认为。
但这并不妨碍您使用token_get_all()函数和所有令牌列表创建自己的 !
我是这样做的:
/**
* Where Are My Variables Assigned!?
* @author Smuuf
*/
class WAMVA {
public function scan($file, $allAssignments = false) {
if (!is_file($file)) return false;
// Get all tokens from the file and initialize result array
$tokens = token_get_all(file_get_contents($file));
$result = array();
// Go through all tokens
foreach ($tokens as $index => $token) {
// Variable token ('$...')
if (isset($token[0]) && $token[0] === T_VARIABLE){
// Skip all whitespaces
$add = 1;
while (is_array($tokens[$index + $add]) && $tokens[$index + $add][0] === T_WHITESPACE) {
$add++;
}
// And if next token is an assigment operator, save the variable token
if (self::isAssignment($tokens[$index + $add])) {
// Get all assignments? Or just the first present in the file?
if ($allAssignments) {
$result[] = array("variable" => substr($token[1], 1), "line" => $token[2]);
} else {
$key = substr($token[1], 1);
if (!isset($result[$key])) $result[$key] = $token[2];
}
}
}
}
return $result;
}
protected function isAssignment($input) {
if ($input == "=") {
return true;
} elseif (is_array($input)) {
// http://www.php.net/manual/en/tokens.php
switch ($input[0]) {
case T_AND_EQUAL:
case T_CONCAT_EQUAL:
case T_DIV_EQUAL:
case T_MINUS_EQUAL:
case T_MOD_EQUAL:
case T_MUL_EQUAL:
case T_OR_EQUAL:
case T_PLUS_EQUAL:
case T_SL_EQUAL:
case T_SR_EQUAL:
case T_XOR_EQUAL:
return true;
}
}
}
}
用法:
print_r(WAMVA::scan("./test.php", true));
输出(allAssignments美元= false):
Array
(
[translation_array] => 11
[target_language] => 12
[lang_abbr] => 41
[translated] => 47
)
输出(allAssignments美元= true):
Array
(
[0] => Array
(
[variable] => translation_array
[line] => 11
)
[1] => Array
(
[variable] => target_language
[line] => 12
)
[2] => Array
(
[variable] => target_language
[line] => 24
)
[3] => Array
(
[variable] => translation_array
[line] => 25
)
[4] => Array
(
[variable] => lang_abbr
[line] => 41
)
[5] => Array
(
[variable] => translated
[line] => 47
)
)