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 you restrict access to certain areas of a website for different user roles in PHP?
- How can you ensure that the web server can interpret PHP code?
- What considerations should be taken into account when implementing a "Forgot Password" feature in PHP without using session_id for users who are not logged in?