PHP Dynamic Variables and Functions
In PHP sometimes you may want to have variable variables or dynamic function calls for whatever reason. PHP allows you to programmatically construct variable and function names. Here is an example of a variable function call from within a class.
$variable = 'myFunc';
$this->{$variable}();
// CALLS CLASS FUNCTION "myFunc"
Sometimes you may want to create variable names on the fly, let's say in a loop where you are updating many records from a form post. This code would make a variable named commonCust and assign it a value of 1:
$custom = 'Cust';
${'common'.$custom} = '1';
echo $commonCust;
// OUTPUTS 1
You’re currently reading “ PHP Dynamic Variables and Functions ,” an entry on BRADINO
- Published:
- 11.20.07 / 1pm
- Category:
- PHP























or use the $$:
function view($path_to_tpl, $arr_var_names) {
foreach( $arr_var_names as $k => $v ) {
$$k = $v;
}
include_once $path_to_tpl;
}
$tpl['name'] = ‘John’;
$tpl['age'] = 23;
view(’/path/to/template.php’, $tpl);
# template.php
/* */
oops, continued…( please join )
just echo the $name and $age variables on the template.php without declaring it globally