【问题标题】:making dynamic defined constants php制作动态定义的常量php
【发布时间】:2017-07-07 00:29:09
【问题描述】:

看看这个变量名修改的语法:

${'a' . 'b'} = 'hello there';
echo $ab;

这会返回"hello there"

但我想动态声明定义的变量。

$error_code = $_GET[error_code]; //for example: 404
define(E404, 'Not found');
echo E{$error_code};

它返回错误,我想在 php 代码上生成 E404 动态并获取它的值。 我不知道我在这里寻找的语法或技术是什么,这使得研究变得困难。

【问题讨论】:

标签: php variables dynamic


【解决方案1】:

您需要调用constant() 从字符串中检索常量的值。您的示例应如下所示:

$error_code = 404;
define('E404', 'Not found');
echo constant("E{$error_code}");

它会显示Not found

【讨论】:

  • 太棒了!认为甚至不可能动态地将 SORT_ASCSORT_DESC 标志提供给数组函数,但很高兴我找到了这个。
【解决方案2】:
<?php
    $ErrorCode = $_GET['error_code']; // Where error_code = 404
    $Errors = array(); // here we are creating a new array.
    $Errors[$ErrorCode] = "Whatever"; // here we are setting a key of the new array, with the keys name being equal to the $ErrorCode Variable

    print_r($Errors); // Would return Array( [404] => Whatever);

    echo $Errors["404"]; // Would return Whatever

?>

【讨论】:

  • 虽然欢迎使用此代码 sn-p,并且可能会提供一些帮助,但它会是 greatly improved if it included an explanation of howwhy 这解决了问题。请记住,您正在为将来的读者回答问题,而不仅仅是现在提问的人!请edit您的答案添加解释,并说明适用的限制和假设。
【解决方案3】:

Php 有一个叫做变量变量的特性。请参阅此链接:http://php.net/manual/en/language.variables.variable.php。它允许将变量名称分配给变量。

【讨论】:

    猜你喜欢
    • 2020-03-13
    • 2011-05-14
    • 1970-01-01
    • 1970-01-01
    • 2012-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多