Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functions that can be called only once

Tags:

function

php

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.

like image 953
Emanuil Rusev Avatar asked Sep 12 '10 16:09

Emanuil Rusev


3 Answers

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

function foo()
{
    static $foo_called = false;
    if (!$foo_called) {
        $foo_called = true;
        // etc.
    }
}
like image 118
GZipp Avatar answered Oct 03 '22 13:10

GZipp


You could use a static variable:

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

    $foo_called = true;

    // do something.
}
like image 29
Gumbo Avatar answered Oct 03 '22 13:10

Gumbo


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

like image 20
PurplePilot Avatar answered Oct 03 '22 13:10

PurplePilot