【问题标题】:list all defined constants from a file in php列出 php 文件中所有已定义的常量
【发布时间】:2015-08-21 22:26:13
【问题描述】:

我有一些包含一些语言常量的 php 文件

define("_SEARCH","Search");
define("_LOGIN","Login");
define("_WRITES","writes");
define("_POSTEDON","Posted on");
define("_NICKNAME","Nickname");

现在我需要读取每个文件并列出所有常量及其值

并返回这样的输出:

常量名: 值是:

所以我认为应该有列出给定 php 文件的所有已定义常量的函数。

我知道诸如 token_get_all 或 get_defined_constants 之类的函数,但我无法做到。

【问题讨论】:

  • 如果您使用get_defined_constants(),什么不起作用?
  • 我确实注意到我已经阅读了这些手册,我在这里关心的是获取(特定 PHP 文件)的所有已定义常量,而不是系统的所有已定义常量
  • 嗯,好的,现在我明白了。这些文件中是否还有其他 PHP 代码/内容?
  • 可能有些行是 cmets,但它们是为语言常量指定的。
  • 虽然我对这个问题表示同情,但我想知道找出特定文件中定义的常量的实际必要性是什么。随着项目的增长,您可能希望将某些常量定义放入另一个文件中的 included 外部文件中,只是为了便于阅读,而无需更改任何功能...

标签: php arrays


【解决方案1】:

如果文件确实只包含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 为我们提供了该数组在文件被包含之前和之后的区别。这正是在该特定文件中定义的所有常量的列表(只要没有任何声明重复,这意味着之前已经定义了具有该确切名称的常量 - 但这无论如何都会导致错误)。

【讨论】:

  • 但是如何知道 php 文件的前后常量是 "user" 。请解释更多关于使用这个
  • 是的,我同意 Mac,假设我们正在使用框架并且文件中的常量已经包含,我们只是不能“排除”文件并“重新包含”
  • 由于这些文件应该是语言文件,我怀疑它们之前是否被包含在内。所以没有问题。 @MacTaylor那个“用户”没有单个常量的名称,它是常量所属的部分(意味着它们是“用户”定义的,而不是由php本身定义的)。 $constants['user'] 是您在代码中通过 define() 定义的所有常量的数组。
  • @NIKO 也许为时已晚,但是... 一个小的修正,如果您使用 array_diff_assoc() 并将第一个值分配为较小的数组,它将返回空 array() 所以在这种情况下我们必须使用: $newConstants = array_diff_assoc( $constantsAfterInclude, $constantsBeforeInclude );
  • @Jaglicic 谢谢,很好。我已经相应地更新了代码。
【解决方案2】:

这是你需要的 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"
}

【讨论】:

  • 这是一个不错的方法,但是我们可以用 str_replace 替换所有 cmets,例如 /* cmets */ 吗?
【解决方案3】:

这里的游戏迟到了,但我遇到了类似的问题。您可以使用 include() 替代/包装函数,将常量记录在可访问的全局数组中。

<?php

function include_build_page_constants($file) {
    global $page_constants ;
    $before = get_defined_constants(true);
    include_once($file);
    $after = get_defined_constants(true);
    if ( isset($after['user']) ) {
        if ( isset($before['user']) ) {
            $current = array_diff_assoc($after['user'],$before['user']);
        }else{
            $current = $after['user'];
        }
        $page_constants[basename($file)]=$current;
    }
}

include_and_build_page_constants('page1.php');
include_and_build_page_constants('page2.php');

// test the array
echo '<pre>'.print_r($page_constants,true).'</pre>';

?>

这将导致类似:

大批 ( [page1.php] => 数组 ( [_SEARCH] => 搜索 [_LOGIN] => 登录 [_WRITES] => 写入 [_POSTEDON] => 发表于 [_NICKNAME] => 昵称 ) [page2.php] => 数组 ( [_THIS] => 富 [_THAT] => 酒吧 ) )

【讨论】:

    【解决方案4】:

    假设您想在运行时执行此操作,您应该查看 PHP Reflection,特别是 ReflectionClass::getConstants(),它可以让您完全按照自己的意愿行事。

    【讨论】:

    • 他使用'define'定义常量,而不是使用'const'关键字。也不在课堂上
    【解决方案5】:

    我也有同样的问题。我从 jondinham 的建议中走出来,但我更喜欢使用正则表达式,因为它更容易控制和灵活。这是我的解决方案版本:

    $text = php_strip_whitespace($fileWithConstants);
    $text = str_replace(array('<?php', '<?', '?>'), '', $text);
    $lines = explode(";", $text);
    $constants = array();
    
    //extract constants from php code
    foreach ($lines as $line) {
        //skip blank lines
        if (strlen(trim($line)) == 0)
            continue;
    
        preg_match('/^define\((\'.*\'|".*"),( )?(.*)\)$/', trim($line), $matches, PREG_OFFSET_CAPTURE);
    
        if ($matches) {
            $constantName = substr($matches[1][0], 1, strlen($matches[1][0]) - 2);
            $constantValue = $matches[3][0];
            $constants[$constantName] = $constantValue;
        }
    }
    print_r($constants);
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-18
    • 1970-01-01
    • 1970-01-01
    • 2012-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多