Search DaTutorials:  
HOME
Php Tutorials
Articles
Basics
Date and Time
File Manipulations
Forms
Functions
General
Interactivity
MySql
Navigation
News,Shoutboxes and Blogs
Language Structure and Data Types
Searching
Security
String Manipulation
User Information and Stats
Search For a Tutorial
Php Reference

Variable functions

PHP supports the concept of variable functions. This means that if a variable name has parentheses appended to it, PHP will look for a function with the same name as whatever the variable evaluates to, and will attempt to execute it. Among other things, this can be used to implement callbacks, function tables, and so forth.

Variable functions won't work with language constructs such as echo(), print(), unset(), isset(), empty(), include(), require() and the like. You need to use your own wrapper function to utilize any of these constructs as variable functions.

Example 12-13. Variable function example

<?php
function foo() {
   echo
"In foo()<br />\n";
}

function
bar($arg = '')
{
   echo
"In bar(); argument was '$arg'.<br />\n";
}

// This is a wrapper function around echo
function echoit($string)
{
   echo
$string;
}

$func = 'foo';
$func();        // This calls foo()

$func = 'bar';
$func('test');  // This calls bar()

$func = 'echoit';
$func('test');  // This calls echoit()
?>

You can also call an object's method by using the variable functions feature.

Example 12-14. Variable method example

<?php
class Foo
{
   function
Variable()
   {
      
$name = 'Bar';
      
$this->$name(); // This calls the Bar() method
  
}
  
   function
Bar()
   {
       echo
"This is Bar";
   }
}

$foo = new Foo();
$funcname = "Variable";
$foo->$funcname();  // This calls $foo->Variable()

?>

See also call_user_func(), variable variables and function_exists().



Copyright © 2001-2004 The PHP Group
All rights reserved.

     Online Advertising | Cheap Car Insurance | Credit Card | Mortgage Calculator | Consolidation Debt
Home     Link To Us     Ad With Us     Contact Us     Tell A Friend     Affiliates     Blog     MsOfficeHelp