Error in PHP ... Fatal error: Uncaught Error: Call to a member function modify () on boolean

2

Personal I have a PHP script that adds another 10 days to a date. The script was working wonderfully well, however, a few days ago I started getting the following error:

  

PHP Fatal error: Uncaught Error: Call to a member function modify ()   on boolean ... line 25.

Line 25 referred to in the error is this:

$dt_mod1->modify('+10 days');

Here is the complete snippet related to this line:

$dt_mod1 = DateTime::createFromFormat('d/m/Y H:i:s', $dt_mod);
$dt_mod1->modify('+10 days');
$dt_mod2 = $dt_mod1->format('d/m/Y');
if ($dt_mod2 == $data_atual ){

    mysqli_query($conexao, "UPDATE 'cadastro' SET 'situacao' = 'CANCELADA' WHERE 'cadastro'.'codigo' = $codigo");
    mysqli_query($conexao, "UPDATE 'cadastro' SET 'dt_mod' = '$data_atual' WHERE 'cadastro'.'codigo' = $codigo");
}
    
asked by anonymous 31.10.2018 / 13:43

1 answer

5

You basically passed an invalid value to the function and did not test it.

Ideally your code would look something like this:

$dt_mod1 = DateTime::createFromFormat('d/m/Y H:i:s', $dt_mod);
if ( $dt_mod1 ) {
   // faz o que tem que fazer
   $dt_mod1->modify('+10 days');
   $dt_mod2 = $dt_mod1->format('d/m/Y');
   // etc
} else {
   // Trata o erro
}


Understanding the problem

See this manual detail, which I marked in bold:

  

Return Valued
  Returns a new instance of DateTime or FALSE in case of failure .

This is what happens in your case, and FALSE does not have the modify method. Precisely for this reason the error mentioned.

If you want details of the error, PHP has a function that you can within else :

if ( $dt_mod1 ) {
   // faz o que tem que fazer
   $dt_mod1->modify('+10 days');
   $dt_mod2 = $dt_mod1->format('d/m/Y');
   // etc
} else {
   echo 'Não foi possível a conversão: ';
   echo htmlentities( date_get_last_errors() );
}


Links to the manual:

link

link

    
31.10.2018 / 13:52