Significantly subsequent to utilizing PHP for a considerable length of time, we unearth capacities and highlights that we didn’t think about. A portion of these can be very valuable, yet underused. In view of that, I’ve assembled a rundown of nine unimaginably valuable PHP capacities and highlights that you ought to be comfortable with.
1. Functions with Arbitrary Number of Arguments
You may definitely realize that PHP permits you to characterize capacities with discretionary arguments. Yet, there is likewise a technique for permitting totally self-assertive number of capacity arguments.
Initially, here is a model with simply discretionary arguments:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
|
// function with 2 optional arguments function foo( $arg1 = '' , $arg2 = '' ) { echo "arg1: $arg1n" ; echo "arg2: $arg2n" ; } foo( 'hello' , 'world' ); /* prints: arg1: hello arg2: world */ foo(); /* prints: arg1: arg2: */ |
Presently, how about we perceive how we can construct a capacity that acknowledges any number of arguments. This time we will use func_get_args():
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
// yes, the argument list can be empty function foo() { // returns an array of all passed arguments $args = func_get_args(); foreach ( $args as $k => $v ) { echo "arg" .( $k +1). ": $vn" ; } } foo(); /* prints nothing */ foo( 'hello' ); /* prints arg1: hello */ foo( 'hello' , 'world' , 'again' ); /* prints arg1: hello arg2: world arg3: again */ |
2. Using Glob() to Find Files
Numerous PHP capacities have long and elucidating names. Anyway it might be difficult to determine what a capacity named glob() does except if you are now acquainted with that term from somewhere else.
Consider it like a more capable form of the scandir() work. It can let you look for records by utilizing designs.
01
02
03
04
05
06
07
08
09
10
11
12
13
|
// get all php files $files = glob ( '*.php' ); print_r( $files ); /* output looks like: Array ( [0] => phptest.php [1] => pi.php [2] => post_output.php [3] => test.php ) */ |
You can fetch multiple file types like this:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
|
// get all php files AND txt files $files = glob ( '*.{php,txt}' , GLOB_BRACE); print_r( $files ); /* output looks like: Array ( [0] => phptest.php [1] => pi.php [2] => post_output.php [3] => test.php [4] => log.txt [5] => test.txt ) */ |
Note that the files can actually be returned with a path, depending on your query:
01
02
03
04
05
06
07
08
09
10
|
$files = glob ( '../images/a*.jpg' ); print_r( $files ); /* output looks like: Array ( [0] => ../images/apple.jpg [1] => ../images/art.jpg ) */ |
If you want to get the full path to each file, you can just call the realpath() function on the returned values:
01
02
03
04
05
06
07
08
09
10
11
12
13
|
$files = glob ( '../images/a*.jpg' ); // applies the function to each array element $files = array_map ( 'realpath' , $files ); print_r( $files ); /* output looks like: Array ( [0] => C:wampwwwimagesapple.jpg [1] => C:wampwwwimagesart.jpg ) */ |
3. Memory Usage Information
By watching the memory utilization of your contents, you might be capable advance your code better.
PHP has a garbage authority and a quite unpredictable memory chief. The measure of memory being utilized by your content. can go here and there during the execution of a content. To get the current memory utilization, we can utilize the memory_get_usage() work, and to get the most noteworthy measure of memory utilized anytime, we can utilize the memory_get_peak_usage() work.
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
echo "Initial: " .memory_get_usage(). " bytes n" ; /* prints Initial: 361400 bytes */ // let's use up some memory for ( $i = 0; $i < 100000; $i ++) { $array []= md5( $i ); } // let's remove half of the array for ( $i = 0; $i < 100000; $i ++) { unset( $array [ $i ]); } echo "Final: " .memory_get_usage(). " bytes n" ; /* prints Final: 885912 bytes */ echo "Peak: " .memory_get_peak_usage(). " bytes n" ; /* prints Peak: 13687072 bytes */ |
4. CPU Usage Information
For this, we will use the getrusage() work. Remember this isn’t available on Windows stages.
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
print_r( getrusage ()); /* prints Array ( [ru_oublock] => 0 [ru_inblock] => 0 [ru_msgsnd] => 2 [ru_msgrcv] => 3 [ru_maxrss] => 12692 [ru_ixrss] => 764 [ru_idrss] => 3864 [ru_minflt] => 94 [ru_majflt] => 0 [ru_nsignals] => 1 [ru_nvcsw] => 67 [ru_nivcsw] => 4 [ru_nswap] => 0 [ru_utime.tv_usec] => 0 [ru_utime.tv_sec] => 0 [ru_stime.tv_usec] => 6269 [ru_stime.tv_sec] => 0 ) */ |
That may look somewhat obscure except if you as of now have a system organization foundation. Here is the clarification of each worth (you don’t have to retain these):
- ru_oublock: square yield activities
- ru_inblock: square information tasks
- ru_msgsnd: messages sent
- ru_msgrcv: messages got
- ru_maxrss: most extreme occupant set size
- ru_ixrss: vital shared memory size
- ru_idrss: vital unshared information size
- ru_minflt: page recovers
- ru_majflt: page deficiencies
- ru_nsignals: signals got
- ru_nvcsw: willful setting switches
- ru_nivcsw: automatic setting switches
- ru_nswap: trades
- ru_utime.tv_usec: client time utilized (microseconds)
- ru_utime.tv_sec: client time utilized (seconds)
- ru_stime.tv_usec: system time utilized (microseconds)
- ru_stime.tv_sec: system time utilized (seconds)
To perceive the amount CPU power the content has devoured, we have to take a gander at the ‘client time’ and ‘system time’ values. The seconds and microseconds divides are given independently as a matter of course. You can separate the microseconds esteem by 1 million, and add it to the seconds esteem, to get the all out seconds as a decimal number.
How about we see a model:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
|
// sleep for 3 seconds (non-busy) sleep(3); $data = getrusage (); echo "User time: " . ( $data [ 'ru_utime.tv_sec' ] + $data [ 'ru_utime.tv_usec' ] / 1000000); echo "System time: " . ( $data [ 'ru_stime.tv_sec' ] + $data [ 'ru_stime.tv_usec' ] / 1000000); /* prints User time: 0.011552 System time: 0 */ |
Despite the fact that the content took around 3 seconds to run, the CPU use was incredibly low. Since during the rest activity, the content really doesn’t consume CPU assets. There are numerous different undertakings that may take constant, however may not utilize CPU time, such as hanging tight for plate tasks. So as you see, the CPU utilization and the genuine length of the runtime are not generally the equivalent.
Here is another model:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
|
// loop 10 million times (busy) for ( $i =0; $i <10000000; $i ++) { } $data = getrusage (); echo "User time: " . ( $data [ 'ru_utime.tv_sec' ] + $data [ 'ru_utime.tv_usec' ] / 1000000); echo "System time: " . ( $data [ 'ru_stime.tv_sec' ] + $data [ 'ru_stime.tv_usec' ] / 1000000); /* prints User time: 1.424592 System time: 0.004204 */ |
That took about 1.4 seconds of CPU time, practically which was all client time, since there were no system calls.
System Time is the measure of time the CPU spends performing system requires the bit for the program’s sake. Here is a case of that:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
|
$start = microtime(true); // keep calling microtime for about 3 seconds while (microtime(true) - $start < 3) { } $data = getrusage (); echo "User time: " . ( $data [ 'ru_utime.tv_sec' ] + $data [ 'ru_utime.tv_usec' ] / 1000000); echo "System time: " . ( $data [ 'ru_stime.tv_sec' ] + $data [ 'ru_stime.tv_usec' ] / 1000000); /* prints User time: 1.088171 System time: 1.675315 */ |
Presently we have a considerable amount of framework time utilization. This is on the grounds that the content calls the microtime() work ordinarily, which plays out a solicitation through the working framework to bring the time.
Additionally you may see the numbers don’t exactly signify 3 seconds. This is on the grounds that there were most likely different processes on the worker too, and the content was not utilizing 100% CPU for the entire span of the 3 seconds.
5. Magic Constants
PHP provides useful magic constants for fetching the current line number (__LINE__
), file path (__FILE__
), directory path (__DIR__
), function name (__FUNCTION__
), class name (__CLASS__
), method name (__METHOD__) and namespace (__NAMESPACE__
).
We won’t spread every single one of these in this article, yet I will show you a couple of utilization cases.
When including other scripts, it is a good idea to utilize the
__FILE__
constant (or also__DIR__
, as of PHP 5.3):
1
2
3
4
5
6
7
|
// this is relative to the loaded script's path // it may cause problems when running scripts from different directories require_once ( 'config/database.php' ); // this is always relative to this file's path // no matter where it was included from require_once (dirname( __FILE__ ) . '/config/database.php' ); |
Using __LINE__
makes debugging easier. You can track down the line numbers:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
|
// some code // ... my_debug( "some debug message" , __LINE__ ); /* prints Line 4: some debug message */ // some more code // ... my_debug( "another debug message" , __LINE__ ); /* prints Line 11: another debug message */ function my_debug( $msg , $line ) { echo "Line $line: $msgn" ; } |
6. Generating Unique ID’s
There might be situations where you have to create a special string. I have seen numerous individuals utilize the md5() work for this, despite the fact that it’s not actually implied for this reason:
1
2
|
// generate unique string echo md5(time() . mt_rand(1,1000000)); |
There is really a PHP function named uniqid() that is intended to be utilized for this.
01
02
03
04
05
06
07
08
09
10
11
|
// generate unique string echo uniqid(); /* prints 4bd67c947233e */ // generate another unique string echo uniqid(); /* prints 4bd67c9472340 */ |
You may see that despite the fact that the strings are remarkable, they appear to be comparative for the initial a few characters. This is on the grounds that the created string is identified with the worker time. This really has a decent reaction, as each new produced id comes later in sequential order request, so they can be arranged.
To lessen the odds of getting a copy, you can pass a prefix, or the subsequent parameter to build entropy:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
|
// with prefix echo uniqid( 'foo_' ); /* prints foo_4bd67d6cd8b8f */ // with more entropy echo uniqid( '' ,true); /* prints 4bd67d6cd8b926.12135106 */ // both echo uniqid( 'bar_' ,true); /* prints bar_4bd67da367b650.43684647 */ |
This function will create shorter strings than md5(), which will likewise spare you some space.
7. Serialization
Have you at any point expected to store an unpredictable variable in a database or a book record? You don’t need to concoct an extravagant answer for convert your clusters or items into designed strings, as PHP as of now has capacities for this reason.
There are two mainstream strategies for serializing factors. Here is a model that utilizes the serialize() and unserialize():
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
// a complex array $myvar = array ( 'hello' , 42, array (1, 'two' ), 'apple' ); // convert to a string $string = serialize( $myvar ); echo $string ; /* prints a:4:{i:0;s:5:"hello";i:1;i:42;i:2;a:2:{i:0;i:1;i:1;s:3:"two";}i:3;s:5:"apple";} */ // you can reproduce the original variable $newvar = unserialize( $string ); print_r( $newvar ); /* prints Array ( [0] => hello [1] => 42 [2] => Array ( [0] => 1 [1] => two ) [3] => apple ) */ |
This was the local PHP serialization strategy. Be that as it may, since JSON has gotten so mainstream as of late, they chose to include support for it in PHP 5.2. Presently you can utilize the json_encode() and json_decode()functions too:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
// a complex array $myvar = array ( 'hello' , 42, array (1, 'two' ), 'apple' ); // convert to a string $string = json_encode( $myvar ); echo $string ; /* prints ["hello",42,[1,"two"],"apple"] */ // you can reproduce the original variable $newvar = json_decode( $string ); print_r( $newvar ); /* prints Array ( [0] => hello [1] => 42 [2] => Array ( [0] => 1 [1] => two ) [3] => apple ) */ |
It is more smaller, and the best part is that good with javascript and numerous different languages. Be that as it may, for complex items, some data might be lost.
8. Compressing Strings
When discussing compression, we normally consider records, for example, ZIP files. It is conceivable to pack long strings in PHP, without including any file documents.
In the accompanying model we will use the gzcompress() and gzuncompress() capacities:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
$string = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc ut elit id mi ultricies adipiscing. Nulla facilisi. Praesent pulvinar, sapien vel feugiat vestibulum, nulla dui pretium orci, non ultricies elit lacus quis ante. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam pretium ullamcorper urna quis iaculis. Etiam ac massa sed turpis tempor luctus. Curabitur sed nibh eu elit mollis congue. Praesent ipsum diam, consectetur vitae ornare a, aliquam a nunc. In id magna pellentesque tellus posuere adipiscing. Sed non mi metus, at lacinia augue. Sed magna nisi, ornare in mollis in, mollis sed nunc. Etiam at justo in leo congue mollis. Nullam in neque eget metus hendrerit scelerisque eu non enim. Ut malesuada lacus eu nulla bibendum id euismod urna sodales. "; $compressed = gzcompress( $string ); echo "Original size: " . strlen ( $string ). "n" ; /* prints Original size: 800 */ echo "Compressed size: " . strlen ( $compressed ). "n" ; /* prints Compressed size: 418 */ // getting it back $original = gzuncompress( $compressed ); |
We had the option to achive practically half size reduction. Additionally the capacities gzencode() and gzdecode() achive comparative outcomes, by utilizing an alternate pressure calculation.
9. Register Shutdown Function
There is a capacity called register_shutdown_function(), which will let you execute some code directly before the content completes the process of running.
Envision that you need to catch some benchmark insights toward the finish of your content execution, for example, how long it took to run:
01
02
03
04
05
06
07
08
09
10
|
// capture the start time $start_time = microtime(true); // do some stuff // ... // display how long the script took echo "execution took: " . (microtime(true) - $start_time ). " seconds." ; |
From the start this may appear to be paltry. You simply add the code to the base of the content and it runs before it wraps up. Notwithstanding, on the off chance that you ever call the leave() work, that code will never run. Likewise, if there is a lethal mistake, or if the content is ended by the client (by squeezing the Stop button in the program), again it may not run.
At the point when you use register_shutdown_function(), your code will execute regardless of why the content has stopped running:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
|
$start_time = microtime(true); register_shutdown_function( 'my_shutdown' ); // do some stuff // ... function my_shutdown() { global $start_time ; echo "execution took: " . (microtime(true) - $start_time ). " seconds." ; } |