'Functions that can be called only once

I've been using the following approach:

$foo_called = false;

function foo()
{
    if($foo_called)
    {
        return;
    }

    $foo_called = true;

    // do something.
}

I've been wondering if a better / different approaches existed.



Solution 1:[1]

You could use a static variable:

function foo() {
    static $foo_called = false;
    if ($foo_called) return;

    $foo_called = true;

    // do something.
}

Solution 2:[2]

Look at the singleton pattern?

from the manual "The Singleton pattern applies to situations in which there needs to be a single instance of a class. The most common example of this is a database connection. Implementing this pattern allows a programmer to make this single instance easily accessible by many other objects."

Solution 3:[3]

I can't think of an equally simple one right away. This is simple and reliable. I suppose you forgot the global there, but otherwise it should work well.

Solution 4:[4]

It depends a lot of the context and the reason you want the function to be called only once.

If your function is there to initialize something or start something, you're approach is fine. An other thing you could do, if you are initializing something, is to test if what you want to initialize exist or no.

function initSomething() {
    if (isSomethingInit()) return;

    // Init Something
}

If you are using those function as callback to something, you can use lambda declaration instead of declaring a function. This will ensure that your function are only called from certain places.

function somethingWithCallback($callback) {
    $callback(5);
}

somethingWithCallback(function ($e) {echo $e;});

Solution 5:[5]

I know the question is old, but I like my solution and want to share it.

$triggered = false;
$trigger = function($callback)use(&$triggered){
    if(!$triggered){
        $callback();
            $triggered = true;
    }
};

foreach(['Hello','World', 'Wuhuu!'] as $value) {
    $value = ' ' . $value;

    $trigger(function()use(&$value){    // will only run once
        $value = trim($value);
    });

    echo $value;
}

Solution 6:[6]

If you are using SESSION, it may help you.

// PHP
function foo(){    
    
    if(isset($_SESSION['foo_was_called']))
    {
       return false;
    }
    
    $_SESSION['foo_was_called'] = true;
  
    // your code ...
}

Solution 7:[7]

Put your functions in a separate file and include_once the functions.php file

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gumbo
Solution 2 PurplePilot
Solution 3 Fanis Hatzidakis
Solution 4 HoLyVieR
Solution 5 Jason Schilling
Solution 6 aldwip34
Solution 7 Garry Hill