简体   繁体   中英

How can a function call itself in PHP?

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

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.

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. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM