The miscellaneous functions that I learned today are all put in a miscellaneous extension in the official documentation. In fact, these functions are not any special extensions, and they can be used without installing anything. They are just some simple functional functions. That's it. Of course, many of the contents are also frequently used by us, so I will take everyone to study together.
Constant operation
The operation of constants is definitely not unfamiliar to our little friends who use PHP development every day. Regardless of whether you are using a framework or writing code yourself, you often use constant-related content.
define("A", "Test A");
var_dump(A); // string(6) "Test A"
var_dump(B); // Warning: Use of undefined constant B - assumed 'B'
var_dump(constant('A')); // string(6) "Test A"
var_dump(constant('B')); // NULL
// PHP Warning: Use of undefined constant B - assumed 'B'
var_dump(defined('A')); // bool(true)
var_dump(defined('B')); // bool(false)
To simply define a constant is to use the define() function. It has two parameters. The first parameter is the name of the constant, and the second parameter is the value of the constant. It should be noted here that the value of a constant can only be a scalar type, that is, content such as numbers and strings, and cannot be a variable or object type, because the content of this type can be changed at any time.
The content of the constant can be printed directly by using the constant name. Of course, we can also use the constant() function to get the content of the constant, which can receive the constant name of the string type parameter.
The defined() function is used to determine whether the specified constant exists. It only has a letter d more than the define() function. Be careful when using it. Don't write this d too much when defining a constant.
For interfaces and classes, you can also use the const keyword inside them to define internal constants.
interface A1{
const TEST = 'Test A1';
}
class A2{
const TEST = 'Test A2';
}
var_dump(constant('A1::TEST')); // string(7) "Test A1"
var_dump(constant('A2::TEST')); // string(7) "Test A2"
var_dump(defined('A1::TEST')); // bool(true)
var_dump(defined('A2::TEST')); // bool(true)
Internal constants have a scope, they only take effect inside the class. And by default, these constants are directly statically typed, so we don't need to add the static keyword separately.
Code highlighting and file format related
We can use a function to make the code achieve the highlighting effect. In fact, it adds code and some format tags to the specified code content.
var_dump(highlight_string('<?php phpinfo(); ?>', true));
// string(195) "<code><span style="color: #000000">
// <span style="color: #0000BB"><?php phpinfo</span><span style="color: #007700">(); </span><span style="color: #0000BB">?></span>
// </span>
// </code>"
The second parameter of highlight_string() is to specify the return type. If we don't give this parameter, its default value is false, so that when highlight_string() is called, it will be output directly instead of returning the content as the return value. In other words, like functions such as phpinfo(), it will print the result directly.
In addition, we can also directly highlight the contents of a file.
var_dump(highlight_file('1.PHP中的一些杂项函数学习.php', true));
// string(10610) "<code><span style="color: #000000">
// <span style="color: #0000BB"><?php<br /><br /><br />define</span><span style="color: #007700">(</span><span style="color: #DD0000">"A"</span><span style="color: #007700">, </span><span style="color: #DD0000">"Test A"</span><span style="color: #007700">);<br /></span><span style="color: #0000BB">var_dump</span><span style="color: #007700">(</span><span style="color: #0000BB">A</span><span style="color: #007700">); </span><span style="color: #FF8000">// string(6) "Test A"<br /></span><span style="color: #0000BB">var_dump</span><span style="color: #007700">(</span><span style="color: #0000BB">B</span><span style=" ……………………………………
var_dump(show_source('1.PHP中的一些杂项函数学习.php', true));
// string(10610) "<code><span style="color: #000000">
// <span style="color: #0000BB"><?php<br /><br /><br />define</span><span style="color: #007700">(</span><span style="color: #DD0000">"A"</span><span style="color: #007700">, </span><span style="color: #DD0000">"Test A"</span><span style="color: #007700">);<br /></span><span style="color: #0000BB">var_dump</span><span style="color: #007700">(</span><span style="color: #0000BB">A</span><span style="color: #007700">); </span><span style="color: #FF8000">// string(6) "Test A"<br /></span><span style="color: #0000BB">var_dump</span><span style="color: #007700">(</span><span style="color: #0000BB">B</span><span style=" ……………………………………
The first parameter of the highlight_file() function requires the path of a file, and the function of the second parameter is the same as that of the second parameter in highlight_string(). In addition, highlight_file() has an alias function called show_source().
In addition to the code highlighting function, there is also a function php_strip_whitespace() that can help us directly remove spaces, line breaks and comments in the code. It's like tools like compressed code.
var_dump(php_strip_whitespace("1.PHP中的一些杂项函数学习.php"));
// string(570) "<?php
// define("A", "Test A"); var_dump(A); var_dump(B); var_dump(constant('A')); var_dump(constant('B')); var_dump(defined('A')); var_dump(defined('B')); interface A1{ const TEST = 'Test A1'; } class A2{ const TEST = 'Test A2'; } var_dump(constant('A1::TEST')); var_dump(constant('A2::TEST')); var_dump(defined('A1::TEST')); …………………………
Time operation function
Among the miscellaneous functions, there are also some time-related operation functions, such as the running time of the system.
echo hrtime(true), PHP_EOL; // 2636292334692
print_r(hrtime());
// Array
// (
// [0] => 2636
// [1] => 292338001
// )
In the previous article, we actually talked about the role of this hrtime() function. It returns the time elapsed since the current operating system was turned on. For example, my computer was turned on in the morning, and only 2636 seconds have passed since it was turned on. It returns the nanosecond level. If you don't add the parameter with the Boolean type of true, it will return in the form of an array. 0 subscript is the number of seconds, and 1 subscript is the number of nanoseconds. And if the true parameter is added, it will directly return the total number of seconds plus the number of nanoseconds in numeric format.
Other time-related functions are functions that suspend program execution, such as the sleep() function that we often use.
$time = microtime(true);
echo $time, PHP_EOL; // 1609723496.283
sleep(1);
echo microtime(true) - $time, PHP_EOL; // 1.0041399002075
usleep(2000);
echo microtime(true) - $time, PHP_EOL; // 1.0062718391418
time_nanosleep(2, 100000);
echo microtime(true) - $time, PHP_EOL; // 3.0067868232727
time_sleep_until(time()+3);
echo microtime(true) - $time, PHP_EOL; // 5.7171077728271
sleep() pauses the execution of the program at intervals of seconds. The other two functions usleep() use microseconds, and time_nanosleep() use nanoseconds to pause. The last parameter required by time_sleep_until() is to pause until the specified time. For example, here we specify the pause after three seconds, and the required parameter is time() + 3 timestamp. Of course, sleep() and usleep() are the most commonly used in daily development. Here you can take it as an extension of your knowledge. Our PHP can achieve nanosecond pauses.
Generate unique ID
I believe that many students often use the function to generate a unique ID, which is the uniqid() function. But do you know its principles and parameters?
var_dump(uniqid()); // string(13) "5ff270b0014b4"
var_dump(uniqid('pre_')); // string(17) "pre_5ff270b0014d7"
var_dump(uniqid('pre_', true)); // string(27) "pre_5ff270b0014df3.11521937"
uniqid() generates a unique ID based on the number of microseconds in the current time, which means that it cannot completely guarantee that the generated ID is unique. Under the premise of large concurrency, it is very likely that multiple requests will arrive within one microsecond, so it is also possible to generate multiple duplicate IDs.
In this case, we can use its parameters to make the generated ID more unique. The first parameter is to specify the prefix of the generated ID. For different services or different load balancing processing machines, we can use different prefixes to distinguish. The second parameter is to add extra entropy at the end of the returned string, which can further enhance the possibility of uniqueness.
Other functions
In addition to the more common and commonly used functions described above, miscellaneous functions also contain other less commonly used content.
System load
We can use a function sys_getloadavg() to view the current operating system load, and the returned result array corresponds to the load of 1m, 5m and 15m in the Linux system.
var_dump(sys_getloadavg());
// array(3) {
// [0]=>
// float(2.98828125)
// [1]=>
// float(2.4775390625)
// [2]=>
// float(2.341796875)
// }
Execute code
eval() This function is the same as eval() in JavaScript regardless of its name or function. It can parse and run PHP code in a string. But it should be noted that it is also a dangerous function. The string to be run must be our own controllable content, and never run content that users can upload.
eval("echo '123', PHP_EOL;"); // 123
Exit interrupt program
exit;
die;
exit(0);
exit("End"); // End
Exit() and die() need not be introduced too much, they have the same function, die() can be regarded as an alias of exit(). If there are no parameters, you can omit the following parentheses. The function of the parameter is to output after the program is interrupted. If the parameter is a string, the content of the string is directly output. If the parameter is a number, it is equivalent to returning the running status code of the program, which is the same concept as the status code in Linux.
Browser information
When we use the browser to access, we can get some information of the browser through the get_browser() function.
var_dump(get_browser(null, true));
// array(15) {
// ["browser_name_regex"]=>
// string(108) "~^mozilla/5\.0 \(.*mac os x 10.15.*\) applewebkit.* \(.*khtml.*like.*gecko.*\) .*version/14\.0.* safari/.*$~"
// ["browser_name_pattern"]=>
// string(88) "Mozilla/5.0 (*Mac OS X 10?15*) applewebkit* (*khtml*like*gecko*) *Version/14.0* Safari/*"
// ["parent"]=>
// string(11) "Safari 14.0"
// ["platform"]=>
// string(5) "macOS"
// ["comment"]=>
// string(11) "Safari 14.0"
// ["browser"]=>
// string(6) "Safari"
// ["browser_maker"]=>
// string(9) "Apple Inc"
// ["version"]=>
// string(4) "14.0"
// ["majorver"]=>
// string(2) "14"
// ["device_type"]=>
// string(7) "Desktop"
// ["device_pointing_method"]=>
// string(5) "mouse"
// ["minorver"]=>
// string(1) "0"
// ["ismobiledevice"]=>
// string(0) ""
// ["istablet"]=>
// string(0) ""
// ["crawler"]=>
// string(0) ""
// }
It should be noted that this function requires the support of a browscap.ini file, which can be http://browscap.org here, and specify the path of browscap in the php.ini file to the one you downloaded This browscap.ini file. This function is very rare, you can just understand it.
Connection information
The last is to view the connection information of the PHP script, that is, the view of the connection information between the script and the client.
ignore_user_abort(true);
while(1){
echo " ";
if (connection_status()!=0){
ob_start();
var_dump(connection_aborted());
$v = ob_get_contents();
ob_end_flush();
file_put_contents("1.txt", date("Y-m-d H:i:s") . " Connection aborted! " . $v . PHP_EOL, FILE_APPEND);
exit;
}
}
// 1.txt
// 2021-01-04 08:56:22 Connection aborted! int(1)
The ignore_user_abort() function is used to set whether to interrupt the execution of the script when the client disconnects. When we visit this test page, we immediately close it on the browser to trigger this function.
The following infinite loop code is used to monitor the status of the current connection. The function connection_status() is used. When its value is 0, that is, the status of CONNECTION_NORMAL is a normal connection status, and when it is not 0 At that time, we recorded it in a log file. connection_aborted() is a function to determine whether the connection is interrupted. This is a function that directly outputs the stream. We need to capture its content through the input and output streams.
Finally, when the browser is closed, the connection-related content is recorded in the file 1.txt. We can view the information in this file.
Summarize
How about it, although today's content is a miscellaneous extension in the PHP document, and the content is indeed very complicated, but they have a lot of content that we often use. Master them well and broaden your horizons. Someday these contents will bring you blessings. Come on, hit the workers.
Test code:
Reference documents:
https://www.php.net/manual/zh/book.misc.php
==============
All media platforms can follow 【Hardcore Project Manager】
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。