Variable variables in PHP - What is their purpose?

后端 未结 4 1433
耶瑟儿~
耶瑟儿~ 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:27

    Sometimes we need software that is extremely flexible and that we can parametrize. You have to prepare the whole thing, of course, but part of it just comes from user input, and we have no time to change the software just because the user needs a new input.

    With variable variables and variable functions you can solve problems that would be much harder to solve without them.

    Quick Example:

    Without variable variables:

    $comment = new stdClass(); // Create an object
    
    $comment->name = sanitize_value($array['name']);
    $comment->email = sanitize_values($array['email']);
    $comment->url = sanitize_values($array['url']);
    $comment->comment_text = sanitize_values($array['comment_text']);
    

    With variable variables

    $comment = new stdClass(); // Create a new object
    
    
    foreach( $array as $key=>$val )
    {
        $comment->$key = sanitize_values($val);
    }
    

提交回复
热议问题