There are 2 functions func_1 and func_2. How to substitute a random number to the function name

$rand = rand(1,2); 

to succeed

 echo func_случайное_число (); 

I wanted to do the following

 $homescore = "1"; $awayscore = "0"; function func_1() { echo $hometeam ." дома с минимальным преимуществом переиграл " . $awayteam; } function func_2() { echo $awayteam ." на выезде минимально проиграл " . $hometeam; } $rand = rand(1,2); if ($homescore > $awayscore) { $scoredif = $homescore - $awayscore; switch ($scoredif) { case 1: //Минимальная победа хозяев $random_function = "func_{$rand}"; echo $random_function(); break; } } 

The essence of all this is the conclusion of the news headline about the football match. If the match ended in a home win, then one of the templates is applied:

 Хозяева победили дома Гостей Гости проиграли на выезде Хозяевам 
  • And why such a perversion ? You have a serious miscalculation in the architecture of your application. - romeo
  • @romeo, and how can you get rid of the distortions in the code without going through them !?) - Eugene Moskvin
  • What is there, let's get to the end: $function_name = "test_{$_POST['malware']}"; echo $function_name(); $function_name = "test_{$_POST['malware']}"; echo $function_name(); - romeo
  • You better write why you need it, it may prompt the right decision, because your path is wrong - korytoff
  • one
    @Eugene Moskvin: выглядит извращение крайней степени Exactly. It is worth thinking how to solve your problem in another way. The names of the functions, and for OOP methods and properties of the object should be specified explicitly, and not with the help of calculations (your case), and especially the substitution of variables with data from the outside. - romeo

2 answers 2

You should pay attention to this article in the documentation:
Accessing functions via variables

Here is an example implementation:

 $rand = rand(1, 2); function test_1 () { return 'test 1'; } function test_2 () { return 'test 2'; } $random_function = "test_{$rand}"; echo $random_function(); 

Eugene Moskvin, unfortunately, from your question it is not possible for me to understand what task you were faced with initially, and therefore I can only answer the question posed. No more, no less.

Please note that you may have chosen far from the most optimal way to solve the task before you. I suggest you stop and think about everything again before using this solution.


Solution after updating the issue

 // Храните данные о результатах матча в массиве. // Так вы сократите число переменных. // Обратите внимание, что у меня очки целочисленные. // Раз над ними будет проводиться операция сравнения, это логично. $match = array( 'home' => array( 'name' => 'Зайцы', 'score' => 3 ), 'guest' => array( 'name' => 'ТрынТрава', 'score' => 0 ) ); // Эта функция возвращает случайный элемент массива. // Замечания по работе штатной функции array_rand почитайте в документации: // http://php.net/manual/ru/function.array-rand.php function array_random($array) { $random_key = mt_rand(0, count($array) - 1); return $array[$random_key]; } // Эта функция возвращает текстовый результат сравнения очков команд function analyze_score_difference($score_a, $score_b) { // Разница по очкам высчитывается по модулю $score_difference = abs($score_a - $score_b); // Разница равна 0? Команды сыграли вничью. if ($score_difference === 0) { return 'equal'; } // Разница равна 1? Команды сыграли с минимальной разницей. if ($score_difference === 1) { return 'minimum-difference'; } // Обычный матч return 'default'; } // Функция возвращает случайное сообщение для результатов матча function get_match_status_message($match) { $messages = array( // Ничья 'equal' => array( // Прямой порядок Хозяин - Гость '%s дома сыграл вничью с %s', // Обратный порядок Гость - Хозяин '%2$s на выезде сыграл вничью с %1$s' ), // Минимальная разница 'minimum-difference' => array( '%s дома с минимальным преимуществом переиграл %s', '%2$s на выезде минимально проиграл %1$s' ), // Обычный матч 'default' => array( '%s дома переиграл %s', '%2$s на выезде проиграл %1$s' ) ); // Анализируем результаты матча $match_result = analyze_score_difference( $match['home']['score'], $match['guest']['score'] ); // Возвращаем случайное сообщение для результатов матча // Документация по sprintf // http://php.net/manual/ru/function.sprintf.php // Обратите внимание на: "Пример #4 Изменение порядка параметров" return sprintf( array_random($messages[$match_result]), $match['home']['name'], $match['guest']['name'] ); } // Вывод результатов матча echo get_match_status_message($match); 

Please note that there are no checks for variables or the existence of keys in an array. In my example, only the most basic functionality. Redo it for yourself.

View an example of work

  • It is not necessary to recommend what should not be in the application. - romeo
  • @romeo, where did you see the "recommendation"? I answered the question posed by referring to the existing article in the documentation. - VenZell
  • You are an experienced developer, and therefore must properly assess the situation. Or are you struggling so much with competition? - romeo
  • @romeo, sorry, I do not understand what kind of competition in question. I admit that in part you are right, but they are right only in that I should have warned the author that maybe he is doing something wrong. I still do not see any recommendations in the formulation of my answer, which, for example, should be done this way and the only way. - VenZell
  • one
    @romeo added a warning to the author - VenZell

Do like this

 $func = "func_".$rand; echo $func();