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.

// 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

  • Digg
  • TwitThis
  • del.icio.us
  • Netvouz
  • description
  • Reddit
  • Furl
  • NewsVine
  • Simpy
  • Slashdot
  • Spurl
  • StumbleUpon
  • YahooMyWeb
  • TailRank
  • Technorati
  • Facebook
  • Google
  • LinkedIn
  • Live
  • MySpace
  • Ping.fm
  • Yahoo! Buzz
  • E-mail this story to a friend!



Home | PHP | PHP Dynamic Variables and Functions