Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a function inside itself?

I have a function that generates a key of 4 characters that has to be unique for each time. In order to do that, the function first generates a key, and then checks a database table to see if it's in use by someone else.

If it's not in use, it returns the key, else, it calls itself again, but this causes the function to do an infinite loop, which is a no-no. Here's the whole function:

function key_generator($length = 4)
{
    // I've subsequently left out the generating code,
    // which is not necesarry in this case

    $key = 'xxxx';

    if ($this->user_model->valid_key($key) == true)
    {
        return $key;
    }
    else
    {
        $this->key_generator(4);
    }
}

What is the correct way to call the function again?

By the way, I'm using CodeIgniter, hence $this.

like image 963
rebellion Avatar asked Oct 23 '09 08:10

rebellion


People also ask

How do you call a function inside itself in Python?

Python also accepts function recursion, which means a defined function can call itself. Recursion is a common mathematical and programming concept. It means that a function calls itself. This has the benefit of meaning that you can loop through data to reach a result.

How do you call a function inside?

To call a function inside another function, define the inner function inside the outer function and invoke it. When using the function keyword, the function gets hoisted to the top of the scope and can be called from anywhere inside of the outer function.

Can I call a function inside itself JavaScript?

Introduction to the JavaScript recursive functionsA recursive function is a function that calls itself until it doesn't. And this technique is called recursion.

Can we call a function inside a function in C?

No you can't have a nested function in C . The closest you can come is to declare a function inside the definition of another function. The definition of that function has to appear outside of any other function body, though.


1 Answers

I would not use recursive functions for retry-scenarios (since you don't reuse the result of the function, it's pointless to use recursion)... It adds a lot of unnecessary overhead. Do something like this:

do {
    $key = ...; // Generate your key here...
} while (!$this->user_model->valid_key($key));

return $key;

If you're near the maximum number of keys, this will result in very long loop times, so you might want to put some kind of max limit.

Oh, and if this is occurring on multiple threads simultaneously and you're checking a database, you should implement table write locking so that the same key can't be inserted twice. Preferably the function that checks whether a key is available should lock, check, and if available write in the same transaction to avoid any collisions.

like image 57
Blixt Avatar answered Oct 05 '22 21:10

Blixt