w3resource

PHP Exercises: Call a given function only once

PHP: Exercise-101 with Solution

Write a PHP program to call a given function only once.

Sample Solution:

PHP Code:

<?php
// Licence: https://bit.ly/2CFA5XY

// Function definition for 'once' that takes a function as a parameter
function once($function)
{
    // Return a closure that encapsulates the original function
    return function (...$args) use ($function) {
        // Static variable to track whether the function has been called
        static $called = false;

        // If the function has been called before, return early without executing the original function
        if ($called) {
            return;
        }

        // Mark the function as called and execute the original function with the provided arguments
        $called = true;
        return $function(...$args);
    };
}

// Anonymous function definition for 'add' that takes two parameters and returns their sum
$add = function ($a, $b) {
    return $a + $b;
};

// Create a 'once' version of the 'add' function
$once = once($add);

// Call the 'once' version of 'add' with arguments and display the result using 'var_dump'
var_dump($once(10, 5));  // Output: int(15)

// Attempt to call the 'once' version of 'add' again with different arguments
// The second call should return early without executing the original function
var_dump($once(20, 10)); // Output: NULL
  
?>

Sample Output:

int(15)
NULL

Flowchart:

Flowchart: Call a given function only once.

PHP Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous:Write a PHP program to curry a function to take arguments in multiple calls.
Next: Write a PHP program to capture a variable number of arguments to a given function.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.