3

I am new with Laravel and PHP so I decide to see the core code and try to read it a little, but when I reached this part, I am confused! how does this function works? $this->getAlias($this->aliases[$abstract]); can a function call itself? wouldn't it be looping?

protected function getAlias($abstract)
    {
        if (! isset($this->aliases[$abstract])) {
            return $abstract;
        }

        return $this->getAlias($this->aliases[$abstract]);
    }

thank you

postsrc
  • 732
  • 3
  • 9
  • 26
  • if in ```return $this->getAlias($this->aliases[$abstract]);``` the supplied argument is different from earlier one what can be the problem for the function to work ? – Prafulla Kumar Sahu Sep 10 '16 at 06:18
  • It's supposed to loop. But it's upon the programmer to prevent it from looping indefinitely. – DanMan Sep 10 '16 at 07:45

2 Answers2

5

You may want to read about recursive functions.

A recursive function is a function that calls itself

This function takes some argument and checks if it has an alias. If it does, it calls itself again and checks if found alias has an alias etc.

Community
  • 1
  • 1
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
1

These are called recursive functions... Which means, a function can call itself until the final condition for the expected output is reached.

A simple example for this would be... Multiplication of 2 until the sum reaches 100.

public function multiplication($a, $sum = 0, $times = 0) {
  if($sum == 100) {
    return $times;
  }
  $sum += $a;
  $times++;
  return multiplication($a, $sum, $times);
}

echo multiplication(2);

Output will be

50

In the function written in the question, it is trying to check if all the abstract value passed as param is set for that current class or not.

Hope you are now clear of the concept. :)

Community
  • 1
  • 1
prateekkathal
  • 3,482
  • 1
  • 20
  • 40