I'm not able to understand braces goal in the situation below and I find no serious documentation about braces usage.
See the example below:
$var = array('a','b','c','d');
foreach($var as $item){
${$item} = array();
}
I'm non understanding ${$item}
meaning.
I've tried with var_dump
before and after foreac开发者_如何学Ch loop but it seems nothing happens.
Any ideas?
It creates 4 empty arrays:
$a, $b, $c, $d // arrays now
Curly braces create a variable with same name as string provided inside the curly braces. In your code, it creates 4 new variables $a,$b,$c,$d by taking strings from the array $var .
Here is an example to see the difference in variables created in your code: http://codepad.org/E2619ufe
<?php
$var = array('a','b','c','d');
$currentState = get_defined_vars();
foreach($var as $item){
${$item} = array();
}
$newState = get_defined_vars();
$newVariables = array_diff(array_keys($newState),array_keys($currentState));
var_dump($newVariables);
?>
Here is an example usage of curly braces: http://codepad.org/KeE75iNP
<?php
${'myVar'} = 12345;
var_dump($myVar);
/* also helpful when the variable name contains $ due to some reason */
${'theCurrency$'} = 4000;
var_dump(${'theCurrency$'});
/* uncomment line below, it will raise syntax error */
//var_dump($theCurrency$);
?>
yes exactly it creates 4 empty arrays , you are creating variables on runtime , thats the usage of braces . here is examples of the usage of braces : braces in php
Anything you put in curly brace will substitute value of the variable.
So the end value will be 4 empty arrays
${item} will become $a, ie: $a = array();
${item} will become $b, ie: $b = array();
${item} will become $c, ie: $c = array();
${item} will become $d, ie: $d = array();
精彩评论