tags:

views:

97

answers:

5

I've been using the following approach:

$foo_called = false;

function foo()
{
    if($this->foo_called) return;

    $this->foo_called = true;

    // do something.
}

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

+2  A: 

You could use a static variable:

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

    $foo_called = true;

    // do something.
}
Gumbo
+1  A: 

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."

PurplePilot
+1  A: 

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.

Fanis
+5  A: 

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

function foo()
{
    static $foo_called = false;
    if (!$foo_called) {
        $foo_called = true;
        // etc.
    }
}
GZipp
You are right. I fixed the snippet to address that.
Emanuil
+1  A: 

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;});
HoLyVieR