PHP Classes

PHP 7 Migration guide Part 3: 11 Changed Functions and 21 New Functions

Recommend this page to a friend!
  Blog PHP Classes blog   RSS 1.0 feed RSS 2.0 feed   Blog PHP 7 Migration guide...   Post a comment Post a comment   See comments See comments (1)   Trackbacks (0)  

Author:

Viewers: 2,290

Last month viewers: 4

Categories: PHP Tutorials

In the first two parts of our series on PHP 7 migration guide we cover backwards incompatible changes and new features.

Read this article to learn more about functions that were changed and other new functions that were added.




Loaded Article
Picture of Atif Shahab Qureshi
By Atif Shahab Qureshi Pakistan

cloudways.com/en/

<email contact>

Contents

Introduction

Changed Functions in PHP 7

New Functions Introduced in PHP 7

Conclusion

PHP 7 logo

Introduction

If you missed the previous parts of this PHP 7 article series, you may want to go back a read the first part on PHP 7 backwards incompatible changes that may break your current code, and the second part on PHP 7 new features.

In this part I cover specific PHP functions that were changed or added because great part of PHP functionality is provided to developers by the means of built-in functions.

Changed Functions in PHP 7

In PHP 7, there are many functions which have undergone a few changes that you should pay attention if you are using them in code that you plan to use in PHP 7. Some functions just add optional parameters, so they preserve backwards compatibility.

1. debug_zval_dump()

It dumps string representation of internal Zend value to output. It will not display 'long' but 'int'. Similarly, it will not display 'double' anymore but 'float'.

2. dirname()

dirname() is used for returning the path of the parent of a directory or file name. Now, you are able to pass a second parameter to this function named levels. With this parameter, you can get the path of the parent directory of N levels above the current. The default value is 1.

3. getrusage()

getrusage is used to get the usage of machine and operating system resources of the current process running PHP, like swap memory, time spent, etc.. Now it also supports Windows.

Syntax:

array getrusage ([ int $who = 0 ] )

4. mktime()

5. gmmktime()

mktime() and gmmktime() are generally used to get timestamp for a date specifying individual date and time values. It used to support the parameter is_dst for specifying whether it should consider daylight savings or not. but since PHP 7 this parameter became invalid, so you no longer should use it.

6. preg_replace()

preg_replace() is a frequently used function in PHP dedicated to the purpose of searching and replacing text using a regular expression. '/e' modifier was used to make the function execute the result as PHP code is no longer supported in PHP 7. You should now use the preg_replace_callback() function for this purpose.

7. setlocale()

This function is for setting locale settings that define things like date and money formats.

/* Set locale to Dutch */
setlocale(LC_ALL, 'nld_nld');

This function was modified in PHP 7 so the category can't be passed as string value anymore. Only LC_* should be used from now on.

8. exec()

9. system()

10. passthru()

exec() is used for executing an external program. For example:

<?php
// outputs the username that owns the running php/httpd process
// (on a system with the "whoami" executable in the path)
echo exec('whoami');
?>

system() is similar to exec() function but with a difference that it also displays output. For example:

<?php
 echo '<pre>';

 // Outputs all the result of shellcommand "ls", and returns
 // the last output line into $last_line. Stores the return value
 // of the shell command in $retval.
 $last_line = system('ls', $retval);

 // Printing additional info
 echo '
 </pre>
 <hr />Last line of the output: ' . $last_line . '
 <hr />Return value: ' . $retval;
?>

passthru() is similar to system() but with a difference that it displays raw output and executes an external program.

In PHP 7 these functions provide NUL byte protection.

11. substr()

If the string character length is equal to start value, then it will return an empty string, while it was to return false.

New Functions Introduced in PHP 7

Here following some new functions introduced in PHP 7.

1. Closure::Call()

Closures are used for representing anonymous functions. Anonymous functions are the functions that are defined without a specific name.

We can use it for binding and calling the closure.

2. random_bytes()

3. random_int()

CSPRNG stands for cryptographically secure pseudo-random number generator. PHP 7 provides functions is used for generating random integers and bytes that are more secure for cryptography applications. For example:

<?php
$bytes = random_bytes(5);
var_dump(bin2hex($bytes));
?>

Output:

string(10) "385e33f741"

In a similar way random_int() generates pseudo-random integers in a cryptographic secure way by. Use it instead of rand(). For example:

<?php
var_dump(random_int(100, 999));
var_dump(random_int(-1000, 0));
?>

Output:

int(248)
int(-898)

4. error_clear_last()

Error handling and logging functions are used to deal with error logging and handling. It enables you to customize your code error reporting features. The logging function allows you to send error messages to files, other machines or by email.

error_clear_last() enables you to clear the most recent error. For example:

<?php
var_dump(error_get_last());
error_clear_last();
var_dump(error_get_last());
@$a = $b;
var_dump(error_get_last());
error_clear_last();
var_dump(error_get_last());
?>

Output:

NULL
NULL
array(4) {
["type"]=>
int(8)
["message"]=>
string(21) "Undefined variable: b"
["file"]=>
string(9) "%s"
["line"]=>
int(6)
}
NULL

5. Generator::getReturn()

Generator can execute code that iterates over sets of data generated dynamically. The generator class provides access to generator objects.

Generator::getReturn() gets the return value of the generator. It has no parameters. For example:

<?php
$gen = (function() {
yield 1;
yield 2;
return 3;
})();
foreach ($gen as $val) {
echo $val, PHP_EOL;
}
echo $gen->getReturn(), PHP_EOL;

Output:

1
2
3

6. gmp_random_seed()

The GMP extension (GNU multiple precision) can manipulate numbers of arbitrary precision.

gmp_random_seed() seeds the random number generator and returns the NULL on success. For example:

<?php
// set the seed
gmp_random_seed(100);
var_dump( gmp_strval( gmp_random(1) ) );
// set the seed to something else
gmp_random_seed( gmp_init( -100 ) );
var_dump( gmp_strval( gmp_random_bits( 10 )));
// set the seed to something invalid
var_dump( gmp_random_seed( 'not a number' ) );

Output:

string(20) "15370156633245019617"
string(3) "683"
Warning: gmp_random_seed(): Unable to convert variable to GMP - string is not an integer in %s on line %d
bool(false)

7. intdiv()

Math functions are used to deal with the calculations or handle values having float and integer data types.

intdiv() is used for returning integer quotient of division by the divisor. For example:

<?php
var_dump( intdiv( 3, 2));
var_dump( intdiv( -3, 2));
var_dump( intdiv( 3, -2));
var_dump( intdiv( -3, -2));
var_dump( intdiv( PHP_INT_MAX, PHP_INT_MAX));
var_dump( intdiv( PHP_INT_MIN, PHP_INT_MIN));
var_dump( intdiv( PHP_INT_MIN, -1));
var_dump( intdiv( 1, 0));
?>

Output:

int(1)
int(-1)
int(-1)
int(1)
int(1)
int(1)
Fatal error: Uncaught ArithmeticError: Division of PHP_INT_MIN by -1 is not an integer in %s on line 8
Fatal error: Uncaught DivisionByZeroError: Division by zero in %s on line 9

8. preg_replace_callback_array()

pcre is a library which implements regular expression pattern manipulation just like Perl 5.

preg_replace_callback_array() matches text with regular expression and replace it using callbacks. This function is similar to preg_replace_callback(). The only difference is that it executes different callbacks on per pattern basis.

9. gc_mem_caches()

10. get_resources()

PHP options and information functions are used for getting information about extensions, versions, and runtime configuration.

gc_mem_caches() reclaims the memory of Zend engine memory manager. It returns a number of memory bytes freed by the call.

get_resources() returns the array of the active resource with resource type. This function is indexed by resource number. For example:

<?php
$fp = tmpfile();
var_dump(get_resources());
?>

Output:

array(1) {
[1]=>
resource(1) of type (stream)
}

11. posix_setrlimit()

POSIX functions provides functions specific to access POSIX compliant systems like Linux.

It is used for setting limits for given system resource. It returns true or false depending upon the status of the operation.

12. ReflectionParameter::gettype()

13. ReflectionParameter::hasType

14. ReflectionFunctionAbstract::getReturnType

15. ReflectionFunctionAbstract::hasReturnType

The reflection API used for retrieving details of classes, methods and properties.

The reflectionparameter::hastype() function is for getting the type of a function parameter. For example:

<?php
function someFunction( int $param, $param2) {}
$reflectionFunc = new ReflectionFunction( 'someFunction' );
$reflectionParams = $reflectionFunc->getParameters();
$reflectionType1 = $reflectionParams[ 0 ]->getType();
$reflectionType2 = $reflectionParams[ 1 ]->getType();
echo $reflectionType1;
var_dump($reflectionType2);

Output:

int
null

ReflectionParameter::hastype just checks whether the associated parameter has any type or not. For example:

<?php
function someFunction(string $param, $param2 = null) {}
$reflectionFunc = new ReflectionFunction( 'someFunction' );
$reflectionParams = $reflectionFunc -> getParameters();
var_dump($reflectionParams[ 0 ]->hasType());
var_dump($reflectionParams[ 1 ]->hasType());

Output:

bool(true)
bool(false)

ReflectionFunctionAbstract::getReturnType function is for getting the specific return type of a function. For example:

<?php
function to_int($param) : int {
return (int) $param;
}
$reflection1 = new ReflectionFunction( 'to_int' );
echo $reflection1->getReturnType();

Output:

int

ReflectionFunctionAbstract::hasReturnType just checks weather the specific return type exists with the reflected function. For example:

<?php
function to_int($param) : int {
return (int) $param;
}
$reflection1 = new ReflectionFunction( 'to_int' );
var_dump( $reflection1->hasReturnType() );

Output:

bool(true)

16. ZipArchive::setcompressionindex

17. ZipArchive::setcompressionname

Zip is an extension for reading or writing zip compressed archives along with the files inside them.

ZipArchive::setcompressionindex basically sets the compression method of an entry method. It returns true or false. For example:

<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip', ZipArchive::CREATE);
if ($res === TRUE) {
$zip->addFromString('foo', 'Some text');
$zip->addFromString('bar', 'Some other text');
$zip->setCompressionIndex(0, ZipArchive::CM_STORE);
$zip->setCompressionIndex(1, ZipArchive::CM_DEFLATE);
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>

ZipArchive::setcompressionname sets the compression method which is defined by its name. It also returns true or false.

18. deflate_init()

19. inflate_init()

20. inflate_add()

21. deflate_add()

Zlib is an extension for reading and writing compressed data and files. All these functions are new commands which were introduced in this extension in PHP 7 to implement the inflate and deflate compression method.

Conclusion

In this article many changed and new functions built-in PHP 7 were described we have discussed changed functions and new functions in PHP 7. These built-in functions are different from PHP user defined functions.

In the next part of this PHP 7 article series, we will be discussing new classes, interfaces, and global constants.

If you liked this article or have a question about the described function, post a comment here.



You need to be a registered user or login to post a comment

Login Immediately with your account on:



Comments:

1. not bad - Mantas (2016-04-27 07:32)
great!... - 0 replies
Read the whole comment and replies



  Blog PHP Classes blog   RSS 1.0 feed RSS 2.0 feed   Blog PHP 7 Migration guide...   Post a comment Post a comment   See comments See comments (1)   Trackbacks (0)