How can I use the value of a variable as constant?

后端 未结 3 1124
花落未央
花落未央 2021-01-16 00:38
  1. I have a PHP site which uses language system based on \"define\" method. For example:

    define(\"_question_1\", \"How old are you?\");
    define(\"_quest         
    
    
            
相关标签:
3条回答
  • 2021-01-16 01:07

    Try constant() it returns the value of a constant, for example:

    var_dump(constant('YourConstantNameHere'));
    

    or with variables

    var_dump(constant($a));
    

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

    0 讨论(0)
  • 2021-01-16 01:08

    Just use constant() to use your variable value as constant, e.g.

    echo constant($a);
    
    0 讨论(0)
  • 2021-01-16 01:22
    1. In PHP you could use variable variable – dynamic variable names.

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

    But it's not good solution. Try not to use dynamic variable names.

    1. May be associative array will be more suitable to you?

      $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. Or declare a Question class and create instances of it.

      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']);
      
    0 讨论(0)
提交回复
热议问题