Variable Function

Last updated on

PHP variable function is a variable that is used to assign a function name with parentheses (). However, the PHP interpreter checks if it contains a callback or a function which should exist in the PHP project. If it doesn’t exist, the interpreter will produce an error.

Let’s see how to do that.

How to Assign a Function to Variable using PHP

According to this concept, PHP allow us to write a string inside a variable which can be called later as a function callback. Here is an example.

$func = "codedtag";

function codedtag() {
  echo "Welcome to CodedTag.com Tutorials.";
}

$func(); // Welcome to CodedTag.com Tutorials.

In this example, I assigned a string value to the variable $func, which contains the function name codedtag. Then, I defined the function with the same name as this string.

In the following line, I called the variable as a function $func(). However, when the interpreter reads it, it will connect the parentheses () with the string inside the variable and consider it as a callback.

Additionally, the PHP interpreter will consider this as a variable function, so if the function is not found during execution, the interpreter will stop executing the code immediately and show you an error message.

Here’s an example to demonstrate this scenario.

$func = "calling_func";
$func();

In this example, I called an undefined function, which is calling_func. That means PHP has to execute this function, calling_func(). But it is not defined yet in the document. So, it will show you the following error.

Fatal error: Uncaught Error: Call to undefined function calling_func() in /tmp/index.php:4 Stack trace: #0 {main} thrown in /tmp/index.php on line ..

Anyway, let’s focus on another aspect of PHP variable functions, which involves the functions inside a class.

Assign a PHP Function of Class as a Variable

In PHP, you can also use the methods of a class as variables with parentheses to call them once an instance of the class is created.

Here is an example:

class team {
   public function group() {
      echo "Our team is ready to start the challenge";
   }
}

$obj = new team();
$group = "group";
$obj->$group();

In this example, we can see that the $group variable stores the name of the method, which can be called by using parentheses.

But, what if the method inside the class contains a static property? Let’s see how it works with the example below.

class team {
   public static function group() {
      echo "Our team is ready to start the challenge";
   }
}

$obj = new team();
$group = "group";
$obj::$group();

One way to call the function using the variable name as a function name is by using the scope resolution operator like this: $obj::$group().

Moreover, there is another method that works on PHP 5.4 and above. It allows us to use a complex callback. For example:

$obj = new team();
$group = array($obj, "group");
$group();

Let’s see how it works with the static method.

class team {
  public static function group() {
    echo "Static Method.";
  }
}
$group = array( "team", "group");
$group();

In both of these examples, the array acts as a function by implementing the class object, with the function being callable once it finds that the main variable has parentheses.

You learned how to assign a function to a PHP variable, but how to pass arguments within? Let’s focus on this in the following section.

Variable Function and Arguments

You can follow the same approach and pass the arguments into the parentheses of the variable function.

$array = array( "item 1", "item 2", "item 3" );
$func = "count";
echo $func($array); // 3

In the above example, the $func variable contains the string name “count”. When invoked with parentheses, PHP looks for the count() function, which requires a countable element as an argument.

However, some PHP predefined callbacks, such as language constructs (e.g., require, empty, include, isset, print, unset, and echo), will not work with variables.

Here is an example:

$value = "Not Empty";
$is_empty = "empty";
var_dump($is_empty());

This will show you a fetal error in PHP like the below.

Fatal error: Uncaught Error: Call to undefined function empty()

Anyway, Let’s summarize it.

Wrapping Up

During this tutorial, you learned what variable functions are and how to use them with a class, static methods, and more. Here is the explanation in a few points:

  • The variable functions in PHP lets you use a variable as a function name. You assign the name of a function to a variable. And then, you call it with parentheses.
  • Assign "codedtag" to a variable $func. Define a function codedtag(). Call $func() to execute codedtag().
  • If the assigned function doesn’t exist, PHP stops. It shows a fatal error. This means the function is undefined.
  • You can assign methods from a class to variables. Call these methods through the variable. Use the scope resolution operator (::) for static methods.
  • Variable functions can take arguments. Include them within the calling parentheses.
  • Some PHP constructs like require and empty can’t be variable functions. Trying this results in a fatal error.

Thank you for reading. Happy Coding!

Frequently Asked Questions (FAQs)

  • What is a variable function in PHP?

    A variable function in PHP is when a variable is assigned a function name with parentheses (). PHP then interprets the variable as a function, executing it if defined.
  • How do I assign a function to a variable in PHP?

    You can assign a function name as a string to a variable, then call it with parentheses. For example:
    $func = "exampleFunction";
    $func(); // Calls exampleFunction()
  • Can you assign a class method to a variable in PHP?

    Yes, class methods can be assigned to variables and called using parentheses once an instance of the class is created.
  • How do you call a static method using a variable function in PHP?

    To call a static method as a variable function, use the scope resolution operator like $class::$methodName().
  • What happens if the function assigned to a variable doesn’t exist in PHP?

    PHP will throw a fatal error if the function name in the variable doesn’t match any defined function, indicating that the function is undefined.
  • Can PHP variable functions take arguments?

    Yes, you can pass arguments within parentheses after the variable function. For example:
    $func = "count";
    echo $func($array); // Passes $array as an argument to count()
  • Can I use PHP constructs like require and empty as variable functions?

    No, PHP constructs like require, empty, include, isset, and others cannot be used as variable functions, and attempting this results in a fatal error.
  • What is a complex callback in PHP variable functions?

    A complex callback involves using an array to reference both a class and method, allowing you to call methods dynamically. For instance:
    $callback = [$obj, "methodName"];
    $callback();
  • How do you handle undefined variable functions in PHP?

    PHP automatically stops execution and throws a fatal error if a variable function is undefined. Always ensure the function exists before calling it.
  • How does PHP interpret a variable as a function?

    PHP checks the variable’s contents for a function name. If it finds a matching function and the variable is followed by (), it executes that function.
  • Can variable functions be used with array operations in PHP?

    Yes, functions like count, which operate on arrays, can be used as variable functions. You assign the function name to a variable and call it with the array as an argument.
  • What’s the difference between regular and variable functions in PHP?

    Regular functions are directly named and called, while variable functions use a variable containing the function name and call it with ().
  • How do you assign a method inside a PHP class to a variable function?

    Assign the method name as a string to a variable and use the variable with parentheses on a class instance:
    $method = "exampleMethod";
    $obj->$method();
Share on: