PHP notes 4--common functions, error handling

Commonly used functions

Output function

print(): Similar to the content provided by echo output, it is essentially a structure (not a function). It returns 1. You don’t need to use parentheses (because the structure is not a function)
. Does not output the type of data, only the value (array printing is used more)

echo print('hello <br/>'); //1
print 'hello <br/>'; //hello
$a = 'hello world'; //hello world
print_r($a)

Time function

date(): Convert the corresponding timestamp (the number of seconds since Greenwich Mean Time in 1970) into the corresponding format according to the
specified format. If no specific timestamp is specified, the current timestamp is interpreted by default
time() : Get the timestamp corresponding to the current time
microtime(): Get the time in microseconds
strtotime(): Convert a string in the specified format into a timestamp (not Chinese)

print date('Y年m月d日 <br/>'); //2020年09月10日
echo '<br/>1';
print time(); //1599747674
echo '<br/>2';
print microtime();//0.06321500  1599747765
echo '<br/>3';
print strtotime('tomorrow 10 hour');//15997475660.47206800

Mathematical function

max(): specify the largest value in the parameter
min(): compare the smaller value of the two numbers
rand(): get a random number, a random integer in the specified interval
mt_rand(): same as rand, but the underlying structure is different , The efficiency is higher than rand (recommended)
round(): rounding
ceil (): rounding up
floor(): rounding down
pow(): finding the specified exponent of the specified number The result: pow(2,8) == 2^8 == 256
abs(): absolute value
sqrt(): find the square root

Function related functions

function_exists(): Determine whether the specified function name exists in the memory (help users not to use a non-existent function, making the code safer)
func_get_arg(): Get the parameter corresponding to the specified value in a custom function – Actual parameter position
func_get_args(): Get all the parameters (array) in the custom function - all the actual parameters
func_num_args(): Get the number of parameters of the current custom function-the actual parameter amount

function test ($a,$b){
    
    
	
	var_dump(func_get_arg(1));//string(1) 
	var_dump(func_get_args());// array(4) { [0]=> int(1) [1]=> string(1) "2" [2]=> int(3) [3]=> int(4) }
	var_dump(func_num_args());// int(4)
	}

function_exists('test')&&test(1,'2',3,4);

Error handling

Refers to when the system (or user) finds an error when executing some code, it will notify the programmer through error handling

Misclassification

1) Syntax error (compilation error): The code written by the user does not conform to PHP's grammatical specification. Syntax error will cause the code to fail during the compilation process, so the code will not be executed (Parse error)
2) Runtime error: the code compiles through , But during the execution of the code, there will be some errors caused by unsatisfied conditions (runtime error)
3) Logical error: The programmer is not standardized enough when writing the code, and there are some logical errors that cause the code to execute normally, but Can't get the desired result

Error code

All the error codes seen are defined as system constants in PHP (can be used directly)
1) System error:
E_PARSE: Parse error, compilation error, code will not execute
E_ERROR: Fatal error, fatal error, will cause the code to fail Continue execution correctly (break at the place where the
error occurred ) E_WARNING: Warning, warning error, will not affect code execution, but may get unexpected results
E_NOTICE: Notice, notify error, will not affect code execution
2) User error:
E_USER_ERROR, E_USER_WARNING , E_USER_NOTICE
The error code that users will use when using custom error triggering (the system will not use it)
3) Other:
E_ALL, which represents all errors (usually used more when performing error control), it is recommended In the development process (development environment),
all error constants (code names) starting with E are actually stored by one byte, and each error occupies a corresponding bit (for example, 0000 0001 means E_ERROR, 0000 0010 means E_WARNING), If you want to perform some error control, you can use bit operations to operate.
Elimination notification level notice: E_ALL & ~E_NOTICE
(Explanation: For example, E_ALL is 11111111, E_NOTICE is 00000100, then ~E_NOTICE is 11111011, and after & is 11111011, it is excluded E_NOTICE)
as long as warnings and notifications: E_WARNING | E_NOTICE
(Explanation: For example, E_WARNING is 00000010, E_NOTICE is 00000100, | after the operation is 00000110, it means that only E_WARNING and E_NOTICE are included)

False trigger

Trigger when the program is running: The system automatically compares the corresponding error information after the error occurs, and outputs it to the user (mainly for code syntax errors and runtime errors).
Human trigger: Know that some logic may go wrong, so use the corresponding judgment code To trigger the response of the error prompt,
consider the trigger method, Trigger_error (error prompt, a user-level error/warning/notice message is generated)

$b =0 ;
if($b ==0){
    
    
	Trigger_error('变量不能为0'); //显示:Notice: 变量不能为0 in C:\E\server\www\test3.php on line 88
	Trigger_error('变量不能为0',E_USER_ERROR);//Fatal error: 变量不能为0 in C:\E\server\www\test3.php on line 89
	}

Error display settings

Error display settings: which errors should be displayed, and how to display them. In PHP, there are actually two ways to set the error handling of the current script
1. PHP configuration file: global configuration: php.ini file
display_errors: whether to display errors
error_reporting : What level of error is displayed

display_errors = On
error_reporting = E_ALL

2. It can be set in the running PHP script: the configuration item level defined in the script is higher than the configuration file (usually during development, it will be controlled and configured in the code)
error_reporting(): set the corresponding error display level, There is no parameter to get the corresponding level of the current system error handling.
Setting example: error_reporting(E_ERROR | E_WARNING | E_PARSE)
ini_set('Configuration item in the configuration file', configuration value)
ini_set('error_reporting',E_ALL);
ini_set('display_errors' ,1);

Error log settings

In the actual production environment, the error will not be directly displayed to users naked:
1. Unfriendly
2. Unsafe: Errors will expose a lot of information on the website (path, file name),
so in the production environment, generally do not display errors (errors) Also less), but it is impossible to avoid errors (all problems will not be found during testing). I don’t want to see it at this time, but I hope that the capture can be modified by the background programmer: it needs to be saved to the log file. , You
need to set the corresponding error_log configuration item in the PHP configuration file or code (ini_set)
1. Turn on the log function

log_errors = On

2. Specify the path (the specified file will not be automatically generated, it must be created manually)

error_log = 'C:/E/server/logs/php_errors.log'

Custom error handling

The simplest error handling: trigger_errors() function, but this function will not prevent the system from reporting errors. The
PHP system provides a mechanism for users to handle errors: user-defined error handling functions, and then add this function to the handle of the operating system error handling , And then the system will use the user-defined error function after encountering an error.

1. How to put user-defined functions into the system? set_error_handler()
2. Custom error handling function, please refer to the document for system requirements

//自定义错误处理机制
header('Content-type:text/html;charset=utf-8');
//方法 前两个参数 必须,后两个参数可选
function my_error($errno,$errstr,$errfile,$errline){
    
    
	//error_reporting() & $errno:如果当前的错误级别($errno)在系统系统处理的错误级别(error_reporting())中存在则处理,如果不存在则直接return出去不进行处理。
	//if(error_reporting()&$errno){
    
    
	//	return false;
	//	}
	//echo 'string';
	switch($errno){
    
    
		case E_USER_ERROR:
				echo '1fatal error in file '.$errfile.' line '.$errline.'<br/>';
				echo 'error info: '.$errstr;
				break;
		case E_USER_WARNING:
				echo '2fatal error in file '.$errfile.' line '.$errline.'<br/>';
				echo 'error info: '.$errstr;
				break;		
		case E_USER_NOTICE:
				echo '3fatal error in file '.$errfile.' line '.$errline.'<br/>';
				echo 'error info: '.$errstr;
				break;				
		case E_ALL:
				echo '4fatal error in file '.$errfile.' line '.$errline.'<br/>';
				echo 'error info: '.$errstr;
				break;		
		default:
				echo '5fatal error in file '.$errfile.' line '.$errline.'<br/>';
				echo 'error info: '.$errstr;
				break;	
		}
	}

//	注册自定义函数:修改错误处理机制
echo  $a;//会报错 Notice: Undefined variable: a in C:\E\server\www\test3.php on line 157
set_error_handler('my_error');//修改错误机制,使用自定义my_error函数处理
echo $a;// 未报错 显示 5fatal error in file C:\E\server\www\test3.php line 163

Currently, it belongs to the simple custom mode. If it is complicated, you can let the user jump to a specified interface after some error that affects the code function occurs.

Guess you like

Origin blog.csdn.net/zhangxm_qz/article/details/108525316