我有一些php文件,其中包含一些语言常量
define("_SEARCH","Search");
define("_LOGIN","Login");
define("_WRITES","writes");
define("_POSTEDON","Posted on");
define("_NICKNAME","Nickname");现在我需要读取每个文件并列出所有常量及其值
并返回如下输出:
常量名称:值为:
所以我认为应该有一个函数来列出给定php文件的所有已定义常量。
我知道像token_get_all或get_defined_constants这样的函数,但我不能这样做。
发布于 2011-09-24 17:17:09
如果这些文件只包含define语句,则可以使用get_defined_constants
function getUserDefinedConstants() {
$constants = get_defined_constants(true);
return (isset($constants['user']) ? $constants['user'] : array());
}
$constantsBeforeInclude = getUserDefinedConstants();
include('file.php');
$constantsAfterInclude = getUserDefinedConstants();
$newConstants = array_diff_assoc($constantsAfterInclude, $constantsBeforeInclude);它所做的基本上是:get_defined_constants(true)给了我们一个包含所有可用常量的数组,按部分(核心,用户,..)排序-键' user‘下的数组给了我们所有用户定义的常量,这些常量是我们在php代码中使用define定义的。array_diff_assoc为我们提供了包含文件之前和之后的数组之间的差异。这正是在特定文件中定义的所有常量的列表(只要没有重复的声明,这意味着以前已经定义了具有该名称的常量-但这无论如何都会导致错误)。
发布于 2011-09-24 17:16:43
这是你需要的php脚本:
<?php
//remove comments
$Text = php_strip_whitespace("your_constants_file.php");
$Text = str_replace("<?php","",$Text);
$Text = str_replace("<?","",$Text);
$Text = str_replace("?>","",$Text);
$Lines = explode(";",$Text);
$Constants = array();
//extract constants from php code
foreach ($Lines as $Line) {
//skip blank lines
if (strlen(trim($Line))==0) continue;
$Line = trim($Line);
//skip non-definition lines
if (strpos($Line,"define(")!==0) continue;
$Line = str_replace("define(\"","",$Line);
//get definition name & value
$Pos = strpos($Line,"\",\"");
$Left = substr($Line,0,$Pos);
$Right = substr($Line,$Pos+3);
$Right = str_replace("\")","",$Right);
$Constants[$Left] = $Right;
}
echo "<pre>";
var_dump($Constants);
echo "</pre>";
?>结果将类似于以下内容:
array(5) {
["_SEARCH"]=>
string(6) "Search"
["_LOGIN"]=>
string(5) "Login"
["_WRITES"]=>
string(6) "writes"
["_POSTEDON"]=>
string(9) "Posted on"
["_NICKNAME"]=>
string(8) "Nickname"
}发布于 2011-09-24 20:32:30
假设你想在运行时做这件事,你应该看一看PHP Reflection,特别是让你做你想做的事情的ReflectionClass::getConstants()。
https://stackoverflow.com/questions/7538049
复制相似问题