T
T
tokyodead2021-06-18 10:46:18
PHP
tokyodead, 2021-06-18 10:46:18

Can you help with a PHP function?

I'm learning from some old lessons, creating a testing system, and the error
Fatal error: Cannot re-assign auto-global variable _POST in C:\OpenServer\domains\testing\functions.php on line 80
This is due to the fact that a global variable is used $_POST
What can be done instead?

Function

function get_test_data_result($test_all_data, $result, $_POST) {
  foreach($result as $q => $a) {
    $test_all_data[$q]['correct_answer'] = $a;
  }
  return $test_all_data;
}

Condition
if( isset($_POST['test']) ) {
  $test = (int)$_POST['test'];
  unset($_POST['test']);
  $result = get_correct_answers($test);
  if( !is_array($result) ) exit('Ошибка!'); // Если такого теста(не массив) не существует, выведет ошибку
  //Данные теста
  $test_all_data = get_test_data($test);
  $test_all_data_result = get_test_data_result($test_all_data, $result, $_POST);
  die;
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
G
galaxy, 2021-06-18
@tokyodead

Superglobal variables ($_GET, $_POST, etc.) are named that way because they are always available from anywhere.
You have named your function parameter _POST and thus you are trying to overwrite a superglobal variable. You can't do that.
Everything will work if you remove _POST from the parameters (and do not pass it when calling - it is already available from everywhere).

V
Vladimir, 2021-06-18
@v__V__v

You have already been told about the error itself, I just want to emphasize one point: by explicitly passing the values ​​of global and superglobal variables into the function, you are doing the right thing . Do this at all times and ignore those who say it's a mistake. they are available everywhere. This will save you a lot of time and nerves. And those who will maintain your code after you too.

S
Sergey Bro, 2021-06-18
@ssenj

The error clearly states `Cannot reassign _POST autoglobal variable`
When declaring a function, rename the $_POST parameter, like so:

function get_test_data_result($test_all_data, $result, $post) { ... }

Or, as advised above, remove it from the parameters. Global variables are available everywhere and inside the function too.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question