What convenient is the US$ design and when it should be used?



  • foreach($_POST as $key => $value){
        $$key = mysql_real_escape_string($value, $base_connection);
    }
    

    That's what's interesting. I looked through the documentation, but I didn't get it. What's the convenience of this US$ design and when it should be used?



  • Documentation - http://php.net/manual/ru/language.variables.variable.php

    The cycle creates a variable whose name is the key of the mass.

    Example:

    $arr = array("name1"=>'test1',"name2"=>'test2',"name3"=>'test3');
    foreach($arr as $key => $value){
        $$key = mysql_real_escape_string($value, $base_connection);
        // строка выше пропускает $value через mysql_real_escape_string
        // и присваивает полученное(экранированное) значение $value переменной с именем 
        // ключа массива (в Вашем примере массивом выступает массив $_POST);
        echo "$$key = '$value';";
    }
    

    As a result, we will get:

    $name1 = 'test1';
    $name2 = 'test2';
    $name3 = 'test3';
    

    UPD:

    How convenient?

    This greatly facilitates the work with the code (also one word "creating variables for the summer." I mean. You can dynamically create different variables. The full example is described in the documentation.

    When you don't use it?

    (1) When it's possible to close the values and you don't check the variable that's being created. The simplest example is when the masses come. $_POST E $_GET And you're recording the variable immediately.

    Example:

    $name1 = 'dima';
    $arr = array("name1"=>'alexey');
    foreach($arr as $key => $value){
        $$key = mysql_real_escape_string($value, $base_connection);
    }
    echo $name1;
    //Выведет 'alexey', т.к. в цикле переменной `$name1` будет присвоено значение `alexey`
    

    Decision - Before writing the meaning, check the name of the variable to be valid or present.

    (2) Unless the problem of ambiguity is solved. I mean, if you write, $$a[1]the processor needs to know if you want to use it. $a[1] as a variable, or you need to be a variable. $$aand then its index [1]

    Decision - Use syntaxis to permit ambiguity: ${$a[1]} If you wish to use $a[1] as variable and ${$a}[1] If you need a variable $$aand then its index [1]


Log in to reply
 

Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2