Functions that can be called only once

2020-07-10 10:10发布

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.

标签: php function
6条回答
Deceive 欺骗
2楼-- · 2020-07-10 10:32

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;
}
查看更多
太酷不给撩
3楼-- · 2020-07-10 10:41

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

function foo()
{
    static $foo_called = false;
    if (!$foo_called) {
        $foo_called = true;
        // etc.
    }
}
查看更多
Luminary・发光体
4楼-- · 2020-07-10 10:41

You could use a static variable:

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

    $foo_called = true;

    // do something.
}
查看更多
forever°为你锁心
5楼-- · 2020-07-10 10:50

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;});
查看更多
混吃等死
6楼-- · 2020-07-10 10:51

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.

查看更多
不美不萌又怎样
7楼-- · 2020-07-10 10:57

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

查看更多
登录 后发表回答