Variable Functions

By appending parentheses () to the end of a variable, PHP looks for a function with the same name and executes it.

 

<?php

	function exampleOne() {
		echo "This is example One <br>" ;
	}

	function exampleTwo() {
		echo "This is example Two <br>" ;
	}

	function exampleThree($var) {
		echo "This is example Three with a passed in value of: $var <br>" ;
	}

	$myVar = "exampleOne" ; //assigns exampleOne to $myVar

	$myVar() ;	//appending parentheses to a variable makes PHP look for a function
				//of the same name initally assigned to the variable
				//which in escence is the same as using exampleOne(); to call the function

	$myVar = "exampleTwo" ; //now we re-assign $myVar with exampleTwo

	$myVar() ;	//which calls the newly assigned variable as the function name
				//same as using exampleTwo(); to call the function

	$myVar = "exampleThree" ;	//again, re-assigning $myVar, now to exampleThree

	$myVar("Potato") ;	//this time we pass a value into the function

	$yourVar = "exampleOne" ;

	$yourVar() ;
?>

Displays:

This is example One 

This is example Two

This is example Three with a passed in value of: Potato

This is example One

Leave a Reply