What are the key differences between PHP 5 and PHP 7 that developers should be aware of when updating their scripts to ensure compatibility?
One key difference between PHP 5 and PHP 7 is the removal of deprecated features such as the use of the "mysql_" extension. Developers should update their scripts to use the improved "mysqli" or "PDO_MySQL" extensions for database connectivity. Additionally, PHP 7 introduces scalar type declarations, return type declarations, and the spaceship operator (<=>) which can enhance code readability and maintainability.
// Replace deprecated "mysql_" functions with "mysqli" or "PDO_MySQL"
// Before:
$conn = mysql_connect('localhost', 'username', 'password');
// After:
$conn = mysqli_connect('localhost', 'username', 'password');
// Use scalar type declarations in function parameters
// Before:
function addNumbers($a, $b) {
return $a + $b;
}
// After:
function addNumbers(int $a, int $b): int {
return $a + $b;
}
// Utilize the spaceship operator for sorting
$numbers = [3, 1, 5, 2];
usort($numbers, function($a, $b) {
return $a <=> $b;
});