JohnSmith
JohnSmith

Reputation: 437

How to call a function in a function

How can I call a function in a function within a class?

My code looks like this (examplified)

    class Test
{

    echo $this->unique();

    public function unique($unique = FALSE)
    {
        function random()
        {
            return 1;
        }

        while($unique === FALSE)
        {
            return $this->random();
            $unique = TRUE;
        }
    }

}

But I get the following error: Call to undefined method Test::random()

Upvotes: 0

Views: 83

Answers (3)

user229044
user229044

Reputation: 239311

It's not $this->random();, it's just random().

Your nested function is not a method of the Test class, it's just a function, local to the method in which you declared it.


Note that your code appears to have some pretty serious flaws.

This code will not work; the while loop will only ever execute once, and it will only execute the return statement. Program flow can never reach the $unique = TRUE line.

    while($unique === FALSE)
    {
        return $this->random();
        $unique = TRUE;
    }

Upvotes: 1

Hassan Sardar
Hassan Sardar

Reputation: 4523

Simply do this:

This is an Example Code:

This is you current main function:

function parentFuntion()
{
  childFuntion();
}

And this is the function which you are trying to call from your main function

function childFuntion()
{

}

Upvotes: 0

Joran Den Houting
Joran Den Houting

Reputation: 3163

Just use random();

class Test
{

    echo $this->unique();

    public function random()
    {
        return 1;
    }


    public function unique($unique = FALSE)
    {

        while($unique === FALSE)
        {
            return random();
            $unique = TRUE;
        }
    }

}

Upvotes: 0

Related Questions