I don't know how to solve this problem. I have the following function in my project:
public static function getTimeAgo($datetime, $full = false) {
$now = new DateTime;
$ago = new DateTime($datetime);
$diff = $now->diff($ago);
$diff->w = floor($diff->d / 7);
$diff->d -= $diff->w * 7;
$string = array(
'y' => 'ano',
'm' => 'mes',
'w' => 'semana',
'd' => 'dia',
'h' => 'hora',
'i' => 'minuto',
's' => 'segundo',
);
foreach ($string as $k => &$v) {
if ($diff->$k) {
if($k == 'm') {
$v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 'es' : '');
} else {
$v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
}
} else {
unset($string[$k]);
}
}
if (!$full) $string = array_slice($string, 0, 1);
return $string ? implode(', ', $string) . ' atrás' : 'agora';
}
Variables $diff->w
and $diff->d
are dynamic properties from the Datetime class which I don't have access to refactor, naturally. What should I do in this case to keep my code in conformity with PHP 8.2+ standards now ?
You can use get_object_vars
to convert DateInterval
to array. Or you can cast it to array.
$diff = get_object_vars($now->diff($ago));
$diff['w'] = floor($diff['d'] / 7);
$diff['d'] -= $diff['w'] * 7;
// ... rest of your code modified to work with array instead of DateInterval object
This should work too:
$diff = (array) $now->diff($ago);
$diff['w'] = floor($diff['d'] / 7);
$diff['d'] -= $diff['w'] * 7;
// ... rest of your code modified to work with array instead of DateInterval object