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.
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.
Just for code clarity, I'd do something like this:
function foo()
{
static $foo_called = false;
if (!$foo_called) {
$foo_called = true;
// etc.
}
}
You could use a static variable:
function foo() {
static $foo_called = false;
if ($foo_called) return;
$foo_called = true;
// do something.
}
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."
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.
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;});
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;
}