开发者

list all defined constants from a file in php

I have some php files that includes some language constants

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

now I need to read each file and list all constants and their values

and to return an output like this :

constant name : value is :

so I think there should be function to list a开发者_如何学Pythonll defined constants of a given php file.

I'm aware of functions like token_get_all or get_defined_constants but i wasn't able to do it.


If the files do contain nothing but define statements, you can use 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);

What it does is basically: get_defined_constants(true) gives us an array of arrays with all available constants, sorted by sections (core, user, ..) - the array under the key 'user' gives us all user-defined constants that we defined in our php code using define, up to that point. array_diff_assoc gives us the difference between this array before and after the file got included.. and that is exactly a list of all constants that got defined in that specific file (as long as there is none of the declarations a duplicate, meaning a constant with that exact name has been defined before - but this would cause an error anyway).


this is the php script you need:

<?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>";
?>

The result will be something similar to this:

array(5) {
  ["_SEARCH"]=>
  string(6) "Search"
  ["_LOGIN"]=>
  string(5) "Login"
  ["_WRITES"]=>
  string(6) "writes"
  ["_POSTEDON"]=>
  string(9) "Posted on"
  ["_NICKNAME"]=>
  string(8) "Nickname"
}


Late to the game here but I had a similar issue. You could use an include() substitute/wrapper function that logs constants in an accessible global array.

<?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>';

?>

This will result in something like:

Array
(
    [page1.php] => Array
        (
            [_SEARCH] => Search
            [_LOGIN] => Login
            [_WRITES] => writes
            [_POSTEDON] => Posted on
            [_NICKNAME] => Nickname
        )

    [page2.php] => Array
        (
            [_THIS] => Foo
            [_THAT] => Bar
        )

)


Assuming that you want to do this on runtime, you should take a look at PHP Reflection, specifically at the ReflectionClass::getConstants() which lets you do exactly what you seem to want.


I too had the same problem. I went from jondinham's suggestion, but I prefer to use regex, as it is a bit easier to control and flexible. Here's my version of the solution:

$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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜