Functions that can be called only once

10,620

Solution 1

Just for code clarity, I'd do something like this:

function foo()
{
    static $foo_called = false;
    if (!$foo_called) {
        $foo_called = true;
        // etc.
    }
}

Solution 2

You could use a static variable:

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

    $foo_called = true;

    // do something.
}

Solution 3

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 4

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 5

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;});
Share:
10,620

Related videos on Youtube

Emanuil Rusev
Author by

Emanuil Rusev

Designer, developer, minimalist, maker of Nota, Historie, Parsedown.

Updated on June 04, 2022

Comments

  • Emanuil Rusev
    Emanuil Rusev over 1 year

    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.