The cart is empty

The evolution of the PHP language continues with each new version, which includes the removal of outdated functions and the addition of new features. The transition from PHP 7 to PHP 8 has brought several significant changes in available functions. This article looks at some of the functions that were in PHP 7 but are no longer available in PHP 8, and provides options for replacing them.

1. Creating Dynamic Variables with $$

Original Approach in PHP 7: In PHP 7, it was common to create dynamic variables using double dollars ($$). This technique allowed for the creation of variables with names defined in other variables.

$name = 'variable';
$$name = 'value';
echo $variable; // Outputs 'value'

New Approach in PHP 8: In PHP 8, developers should prefer more explicit and safer ways of working with variables to avoid potential security risks and ambiguities. One option is to use arrays or objects for dynamic storage of values.

$data = [];
$name = 'variable';
$data[$name] = 'value';
echo $data['variable']; // Outputs 'value'

2. The each() Function

Original Approach in PHP 7: The each() function was frequently used in PHP 7 for iterating over arrays. This function returned the current key and value and moved the array pointer forward.

$array = ['a' => 1, 'b' => 2];
while (list($key, $value) = each($array)) {
    echo "$key => $value\n";
}

New Approach in PHP 8: The each() function was deprecated and removed in PHP 8. It is now recommended to use either foreach or a combination of key(), current(), and next() functions for iteration.

$array = ['a' => 1, 'b' => 2];
foreach ($array as $key => $value) {
    echo "$key => $value\n";
}

3. The create_function()

Original Approach in PHP 7: create_function() was a function in PHP 7 that allowed the creation of an anonymous function from a string. This use was often criticized for potential security risks.

$func = create_function('$a', 'return $a + 1;');
echo $func(1); // Outputs 2

New Approach in PHP 8: In PHP 8, it is recommended to use Closure or anonymous functions, which are safer and more readable.

$func = fn($a) => $a + 1;
echo $func(1); // Outputs 2

4. get_magic_quotes_gpc() and get_magic_quotes_runtime()

Original Approach in PHP 7: Magic quotes were a mechanism that automatically escaped incoming data. The functions get_magic_quotes_gpc() and get_magic_quotes_runtime() were used to determine if magic quotes were active.

if (get_magic_quotes_gpc()) {
    $data = stripslashes($data);
}

New Approach in PHP 8: Magic quotes have been completely removed from PHP. Developers are now recommended to sanitize and escape incoming data explicitly using functions like htmlspecialchars() or filter_input().

$data = htmlspecialchars($data, ENT_QUOTES, 'UTF-8');

These changes in PHP 8 lead to safer and more straightforward code but require developers to familiarize themselves with new practices and update old code according to new standards.