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 JSON Handling with json_encode & json_decode

    JSON is used in most of your web applications for dealing with data, and so, in a way, PHP JSON…

    PHP NOT ( ! ) Operator: A Comprehensive Guide

    The NOT operator in PHP (!) provides the reverse of whatever truth value is given by a certain expression. It’s…

    PHP filter_input: How to Validate Input Securely

    User input can be risky. Hackers exploit weak validation to inject malicious data. PHP filter_input() helps you sanitize and validate…

    PHP fread Function: How to Read Files in PHP

    In some cases, you need to handle a lot of data or simply try to open a file, or read…

    PHP Math: Essential Functions with Examples

    PHP math may sound like a pretty simple thing, but I assure you it's a set of tools that will…

    PHP array_intersect Function: How it Works with Examples

    The PHP array_intersect function finds common values in arrays and returns matches as a new array. Understand the array_intersect in…

    PHP For Loop: Run Code Using a Counter with Examples

    You may need to repeat tasks in PHP. The PHP for loop solves this by letting you run code many…

    PHP array_change_key_case: Change Array Key Cases

    The array_change_key_case function in PHP changes all array keys to lowercase or uppercase for consistent data use. Understand the array_change_key_case…

    PHP trim(): How to remove Whitespace from String

    Early PHP scripts often failed because of extra spaces or line breaks in strings. These issues came from user input…

    PHP continue Statement: How to Skip Steps in Iteration

    The PHP continue statement skips the rest of the loop in the current cycle. It jumps to the next cycle…

    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.