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

后端 未结 3 1156
花落未央
花落未央 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条回答
  •  猫巷女王i
    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']);
      

提交回复
热议问题