Variable Variables in PHP

The term variable variables comes from the PHP manual (read it.)

When I describe code as dynamic I’m referring to the concept of having code which generates other code during execution.

My reasons for writing about Variable Variables in PHP:

  1. The topic is similar to other obscure PHP features (such as that of calling functions dynamically.)
  2. Implementing variable variables differs syntactically when dealing with OOP — as opposed to in procedural code.
  3. Some PHP design patterns use it.
  4. To understand the CI_Controller class.

Here’s a procedural example:

$a = 'hello';
$$a = 'world';
echo "$a ${$a}"; // output: hello world
echo "$a $hello"; // output: hello world

Here’s an OOP example:

class CI_Controller {

	private static $instance;

	 * Constructor
	public function __construct()
		self::$instance =& $this;
		// Assign all the class objects that were instantiated by the
		// bootstrap file (CodeIgniter.php) to local class variables
		// so that CI can run as one big super object.
		foreach (is_loaded() as $var => $class)
			$this->$var =& load_class($class);

		$this->load =& load_class('Loader', 'core');

		log_message('debug', "Controller Class Initialized");

	public static function &get_instance()
		return self::$instance;

The line which uses variable variables is:

$this->$var =& load_class($class);

Notice it’s creating a new property for the object. The class to which this object belongs does not have that property.


About samehramzylabib

See About on
This entry was posted in PHP Data Value Types, PHP Language Constructs. Bookmark the permalink.


Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s