Variable variables in PHP - What is their purpose?

后端 未结 4 1443
耶瑟儿~
耶瑟儿~ 2020-12-03 14:43

In PHP there\'s a functionality officially called \"Variable Variables\" where one can assign variable variables. A variable variable takes the value of one variable as the

4条回答
  •  星月不相逢
    2020-12-03 15:25

    According to @Faiz answer (which I accepted as the formal answer to my question) I created the following sample example.

    If I had the class Customer:

    class Customer
    {
      public $firstname;
      public $lastname;
      public $country;
      public $gender;
      ...
    }
    

    and the web HTML form with INPUT/SELECT fields having names 'firstname','lastname','country', 'gender'...

    Man Woman ...

    usually in my action script I would map these form fields into class variables one by one as:

    $Customer=new Customer();
    $Customer->firstname=$_POST['firstname'];
    $Customer->lastname=$_POST['lastname'];
    $Customer->country=$_POST['country'];
    $Customer->gender=$_POST['gender'];
    ...
    $Customer->create();
    

    But using variable variables I can easily map all associative array values (there could be a lot of them which is error prone) into class variables using the following one line foreach loop;

    $Customer=new Customer();
    foreach($_POST as $key=>$value) $Customer->$key=$value;
    $Customer->create();
    

    Note: For the sake of answer (logic) simplicity and clearness I omitted $_POST values sanitization.

提交回复
热议问题