PHP Dynamic Variables and Functions

Like this blog? Consider exploring one of our sponsored banner ads...

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.

// DYNAMIC FUNCTION CALL
 
$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:

// DYNAMIC VARIABLE CREATION
 
$custom = 'Cust';
 
${'common'.$custom} = '1'; 
 
echo $commonCust;
 
// OUTPUTS 1

About this entry