2

如何将单个 php 文件中定义的所有常量放入数组中?
这是一个定义常量的 php 文件。
我想把这个页面中的所有常量放到一个数组中;
我该怎么做?

<?php 
/**
 *  hello wolrd
 ----------------------------------------
 */

define('HELLO_WORLD','hello world');
define('GOOD_BOOD','
    very good
');
define(
    'JY_CREDITS_HTML',
    '
        <p>hello wrold</p>
        <div class="good">
            <span>world</span>
        </div>

    '
);
// define('META_KEY','Wat adidi');

define('XXX',"xxx")

/* 
    hello world
 */
?>

结果应该是

<?php 
    $result=array(
        'HELLO_WORLD' => 'hello wrold',
        'GOOD_BOOD' => 'very good',
        'JY_CREDITS_HTML' =>'....',
        'XXX'=>'xxx'
    );

 ?>
4

5 回答 5

5
print_r( get_defined_constants(true)['user'] );
于 2013-05-23T11:51:16.490 回答
1
<?php
print_r(get_defined_constants(true));
?>
于 2013-05-23T11:52:16.017 回答
1

你总是可以使用类似的东西: -

define('HELLO_WORLD','hello world');

define('GOOD_BOOD','
    very good
');

define(
'JY_CREDITS_HTML',
'
    <p>hello wrold</p>
    <div class="good">
        <span>world</span>
    </div>

'
);

define('XXX',"xxx");
$result = get_defined_constants(true);
if(isset($result['user'])){
    $result = $result['user']; //just incase there are no user constants set.
}

var_dump($result);

输出:-

array (size=4)
  'HELLO_WORLD' => string 'hello world' (length=11)
  'GOOD_BOOD' => string '
    very good
' (length=17)
  'JY_CREDITS_HTML' => string '
    <p>hello wrold</p>
    <div class="good">
        <span>world</span>
    </div>

' (length=92)
  'XXX' => string 'xxx' (length=3)

见这里http://www.php.net/manual/en/function.get-defined-constants.php

于 2013-05-23T11:53:07.950 回答
1
include('hello_world.php');   
$constants = get_defined_constants();

在与常量相同的脚本中工作时不需要 Include()。

于 2013-05-23T11:54:44.160 回答
1
<?php
   $user_def_cnst=get_defined_constants(true)['user'];
   print_r($user_def_cnst);
?>
于 2013-05-23T11:57:59.293 回答