I am trying to call function inside itself for my Murder minigame, but my server get restarted after I try to use it. How can I do it correctly? Code PHP: public function selectDetective(){ $keys = array_rand($this->players, 1); if($this->players[$keys]->getName() !== $this->murder) { $name = $this->players[$keys]->getName(); return $this->detective = $name; }else{ return $this->selectDetective(); }}
I dont know if it is error , but console display this: Code: ./start.sh: line 57: 1588 Segmentation fault "$PHP_BINARY" "$POCKETMINE_FILE" $@
The error you posted above is an indication you have a recursive function that never stops. $this->players[$keys]->getName() is apparently always $this->murder. We can help you if you post a snippet of what $this->murder is defined like.
Also note that testing this will crash if you do it alone. If you select the murderer, you're the only player in the array, so you become murderer. You're then always murderer when it starts that function, so it keeps going forever and utimately gets a segmentation fault.
Avoid using recursion unless it is necessary. Most of the time it can be avoided by a while loop. Even if you really need recursion, unless you are definitely sure that your recursion won't exceed the limit (i.e. it will only recurse for a few times), use tail recursion instead.
1. Do not re-invent the wheel. 2. PHP functions will probably handle the loops better than you do and are slightly faster because they're written in C. Example: array_merge. Instead of foreach merging two or more array, you can use array_merge to your advantage (I recommend you reading the PHP documentation, this is a very vague example). PHP: //Before$array = [1, 2, 3, 4, 5];$array2 = [6, 7, 8, 9, 10];$array3 = [];foreach($array2 as $value){ $array[] = $value;}//After$array3 = array_merge($array, $array2); PHP: //Before:$array = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]];$newarray = [];foreach($array as $anotherarray){ foreach($anotherarray as $value){ $newarray[] = $value; }}//After:$newarray = array_merge(...$array);