【问题标题】:How can I use the value of a variable as constant?如何将变量的值用作常量?
【发布时间】:2015-08-15 14:01:33
【问题描述】:
  1. 我有一个 PHP 站点,它使用基于“定义”方法的语言系统。 例如:

    define("_question_1", "How old are you?");
    define("_question_2", "Question 2?");
    define("_question_3", "Question 3?");
    ....
    define("_question_10", "Question 10?");
    
  2. 我有 5-10 个问题需要问。我需要选择我想问的问题。所以我对我的数据库进行了查询。比如:

    SELECT q_title FROM questions_db WHERE id=3 OR id=10;
    

    数据库返回两个 TEXT(!) 值:

    _question_3, _question_10
    

    我保存到:

    $a = _question_3; 
    $b = _question_10;
    
  3. 接下来我需要显示之前定义的描述文本。当我使用 _question_3 作为 VARIABLE 时,它的工作方式如下:

    echo ""._question_3.""; //returns "Question 3?"
    

    但我只有 _question_3 作为 TEXT 值,它的工作原理如下:

    echo "".$a.""; //returns "_question_3"
    

问题:如何将文本值转换为 PHP 变量并制作类似的东西?

    define("_question_3", "Question 3?");
    $a = _question_3; //text value
    //do something with $a.... 
    echo "".$a.""; //returns "Question 3?"

感谢您的帮助。 附言不明白的请改标题。

【问题讨论】:

    标签: php variables constants


    【解决方案1】:

    只需使用constant() 将变量值用作常量,例如

    echo constant($a);
    

    【讨论】:

    • 太棒了!作品!这就是我需要的!
    【解决方案2】:
    1. 在 PHP 中你可以使用变量变量——动态变量名。

      $a = '_question_3'; 
      $b = 'Question 3?';
      
      $$a = $b;
      echo $b;
      // prints "Question 3?"
      echo $_question_3;
      // prints "Question 3?"
      

    但这不是一个好的解决方案。尽量不要使用动态变量名。

    1. 可能关联数组会更适合你?

      $questions = []; // Creating an empty array
      $questions['_question_3']['question'] = 'Question 3?'; // Storing a question
      $questions['_question_3']['answers'] = [ // Adding answers
          'Answer 1',
          'Answer 2',
          'Answer 3'
      ];
      
    2. 或者声明一个Question 类并创建它的实例。

      class Question
      {
        public $Question;
      
        public $Answers;
      
        __construct($question, $answers)
        {
           $this->Question = $question;
           $this->Answers = $answers;
        }
      }
      
      $q1 = new Question('Question 1?', ['Answer 1', 'Answer 2', 'Answer 3']);
      

    【讨论】:

    • 第二种方法对我不起作用,因为我希望有可能将问题存储在数据库中并在管理面板中进行编辑。
    • 什么原因阻止你这样做?
    • 由于第一种方式 - 我怎么知道保存到 $b 的值是多少?
    • 上面的答案是我需要的答案!也感谢您的帮助——我会考虑在类似情况下使用关联数组的未来。
    • 好的,很高兴您的问题得到了解答。但是你做错了。常量不是为此而设计的。你最好找到更合适、更合适的方法来实现你的算法。
    【解决方案3】:

    试试constant()它返回一个常量的值,例如:

    var_dump(constant('YourConstantNameHere'));
    

    或带变量

    var_dump(constant($a));
    

    http://www.php.net/manual/en/function.constant.php

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-06
      • 2020-04-21
      • 1970-01-01
      • 1970-01-01
      • 2019-09-02
      • 1970-01-01
      相关资源
      最近更新 更多