PHP Assign Function to Variable – Examples and Explanation

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!

    Similar Reads

    PHP abs Function: How to Get Absolute Values

    The abs() function in PHP gives you a number without its sign — it always returns a positive value. That…

    PHP sizeof: How to Count Elements in Arrays with Examples

    The sizeof function in PHP exists to help developers know how many items an array holds. Understand the sizeof Function…

    PHP fopen: Understanding fopen Modes

    PHP has great tools to handle external files such as opening, writing, deleting and more else, in this tutorial we…

    PHP array_diff_key Function: How it Works with Examples

    PHP array_diff_key compares arrays and removes elements that share the same key. It checks only keys and keeps the values…

    PHP Bitwise Operators: AND, OR, XOR, NOT with Examples

    Bitwise operators use symbols like &, |, and ^, and they work at the binary level. But once you understand…

    PHP Assignment Operators: A Complete Guide

    The assignment operators are the sets of gears that keep your code well-oiled and running when deep in PHP, allowing…

    PHP array_key_exists: How it Works with Examples

    The PHP array_key_exists function checks a given key in an array and tells if that key exists or not. Understand…

    File Handling in PHP

    File Handling in PHP is an important tool especially when you need to manage files such as reading, writing, or…

    PHP Escape Characters: How to Escape Special Characters

    Escape characters appeared in PHP because some symbols in strings serve special purposes. For example, a quote can end a…

    Mastering PHP’s Do-While Loop: Examples and Explanation

    The PHP do-while loop is a type of loop that executes a block of code at least once, and then…

    Previous Article

    Parameters and Arguments in PHP: What’s the Difference?

    Next Article

    PHP Variadic Functions: Use Unlimited Arguments

    Write a Comment

    Leave a Comment

    Your email address will not be published. Required fields are marked *


    Subscribe to Get Updates

    Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
    No spam. Unsubscribe anytime.