How can the code snippet be refactored to utilize more modern PHP features like DateTime objects for age calculation?
The code snippet can be refactored to utilize more modern PHP features like DateTime objects for age calculation. This involves creating DateTime objects for the current date and the user's birthdate, calculating the difference between the two dates, and then extracting the years from the difference to get the user's age.
function calculate_age($birthdate) {
$currentDate = new DateTime();
$birthDate = new DateTime($birthdate);
$age = $currentDate->diff($birthDate)->y;
return $age;
}
$birthdate = '1990-05-15';
$age = calculate_age($birthdate);
echo "The user's age is: " . $age;
Related Questions
- How can PHP developers ensure proper context switching and data formatting when dynamically generating HTML tables from database results?
- How does strtr() in PHP differ from str_ireplace in handling multiple strings for replacement?
- What role does the isset() function play in handling URL parameters in PHP scripts?