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

    How to Update MySQL Data with PHP?

    Understanding how to update data in PHP and MySQL is like editing a draft—it is all about tweaking the right…

    PHP Callable & Callback: Pass a Function to Another

    The callback in PHP lets you pass functions as arguments and reuse code. It helps you to control how tasks…

    PHP Switch | How the Switch Statement Works in PHP

    The PHP switch statement is multiple conditions to only execute one block if its condition generating a true boolean value.…

    PHP Logical Operators | Understanding the 6 Logical Operators

    The PHP logical operators are operands that can be used to check two or more expressions together. For examples (…

    PHP Type Casting: How to Convert Variables in PHP

    Type casting in PHP refers to the process of converting a variable from one data type to another. This is…

    MongoDB CRUD with PHP: Create, Read, Update, and Delete

    PHP gives us the ability to work with MongoDB, highlighting the importance of CRUD (Create, Read, Update, Delete) operations for…

    PHP range Function: Create Arrays with Sequence Values

    The PHP range function helps you make sequences. Without it, you would write loops every time you need numbers or…

    PHP strpos Function: How it Works with Examples

    Sometimes the string you expect is there, but strpos function gives a surprise in PHP. It may show the result…

    PHP Singleton Pattern: How to Use with Examples

    The PHP singleton design pattern makes sure that the class has only one instance and provides a global access point…

    PHP htmlspecialchars Function: Prevent XSS in HTML Output

    A PHP script can break the page or allow code injection if it outputs user input directly into HTML. The…

    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.