可以动态定义常量吗?

时间:2013-06-01 15:31:41

标签: php

在php中,可以随时定义常量。这些年来,我只使用它们来存储数据库登录信息。它们被设置在一个从未被触及的文件中。

但如果我这样做可以:

if ($userName == $dbUserName) {
define('userName', 'myUserNameHere');
}

然后:

    myFunk();

    function myFunk()
//I'm actually trying to avoid tons of arguments here. 
        If it's a constant, it's available without having to use global or pass it through args.
            {
            echo userName;
            }

3 个答案:

答案 0 :(得分:1)

通常,是的,但您应该确保始终定义默认值。

if ($condition == true)
{
  define('FOO', $foo);
}
else
{
  define('FOO', null);
}

另外,按照惯例,常量都是大写的。

然而,过分依赖任何类型的全局变量通常会导致代码难以操作,难以维护。

答案 1 :(得分:0)

是的,您可以有条件地创建定义

if (i_am_debugging()) define('DEBUG', 'Level7');

,否则什么都不做。

然后,您可以通过PHP 定义的函数轻松检查它是否已定义

if (defined('DEBUG')) {
   if (DEBUG == 'Level1') ...
}

答案 2 :(得分:-1)

如果我是你,我会这样做:

<?php

function test ()
{
     echo $GLOBALS['username'];
}


$username = 'foo';

test(); // echo 'foo';

用户名听起来很像动态变量。常数,因为隐含的名称是一个在整个程序中具有不变的平均值的值