PHP Functions, Arrays, and Error Handling: Simple and Practical Development Tips and Error Handling

Table of contents

PHP function

The basic concept of the function:

Function definition syntax:

Function naming relationship:

Detailed parameters

keepsake

Arguments

​edit

Defaults

pass by reference

function body

function return value

scope

static variable

variable function

anonymous function

basic concept

Closure

pseudo type

Library Functions

functions for output

function of time

functions for numbers

functions about functions

PHP error handling

Misclassification

error code

wrong trigger

Error display settings

Error log settings

Custom Error Handling

string definition

string escape

The difference between single quotes and double quotes:

Rules for identifying variables with double quotes:

Rules for structurally defining string variables:

string length problem

String related functions

array

The concept of an array

array definition syntax

PHP array features

Multidimensional Arrays

Two-dimensional array

Multidimensional Arrays

Alien array (irregular array)

array traversal

The basic meaning of traversal

Foreach traversal syntax

Foreach traversal principle

For loop through the array

Array-related functions:


PHP function

The basic concept of the function:

function is a grammatical structure that encapsulates the code block (multiple lines of code) that implements a certain function into a structure to realize code reuse.

Function definition syntax:

Functions have several corresponding key points: function keyword, function name, parameters (formal parameters and actual parameters), function body and return value

Grammar format:

function 函数名(参数)
//函数体
//返回值 :return 结果

The purpose of defining a function:

A function is implemented using a function

For example:

<?php
function display(){
    echo "hello world";
    //没有返回值
}
display();
?>

 

The function is called when the function name is encountered in the code execution phase, not in the compilation phase

Note: The function call can be before the function definition; that is, even if the function call is called before the function implementation, it can be output normally.

Reason: compilation and execution are separate (compile first, then execute)

Function naming relationship:

Naming convention: It consists of letters, numbers, and underscores, and cannot begin with a number.

Two commonly used naming methods:

1. Camel case method: except the first word on the left, capitalize the first letter of all subsequent words; showPartentinfo();

2. Underline method L words are connected by underline: show_parent_info();

Detailed parameters

Parameters are divided into two categories: formal parameters and actual parameters

keepsake

Formal parameters, parameters without practical significance, are parameters in function definition

Arguments

Actual parameter: the actual wipe, the parameter with actual data meaning, is the parameter used when the function is called

The relationship between the two:

The formal parameter is the carrier of the actual parameter; when the actual parameter is called, it usually needs to be passed into the function to participate in the calculation, so it is necessary to find the location of the actual data inside the function to find the data itself; when the actual call is made, the data It is passed to the formal parameter in the form of an actual parameter, and copied to the formal parameter, so that the internal data of the function can be used from the outside.

For example:

<?php
//函数参数
//定义函数
function add($arg1,$arg2)//两个形参
{
   echo  $arg1+$arg2,'<br/>';
}
add(1,2);
$a=100;
$b=89;
add($a,$b);
?>

Defaults

default: refers to the default value of the formal parameter. When the function is defined, an initial copy is made to the parameter; if the parameter (actual parameter) passed in by the actual call is not provided, the formal parameter will use the value at the time of definition. Enter the internal parameter operation of the function.

<php?
function jian($num1=0,$num2=0)
{
    echo $num1=$num2,'<br/>';
}
//调用时默认值如果存在,可以不同传入
jian();
jian(2,1);
?>

Notice:

1. The default value is placed at the end. The formal parameter on the left cannot have a default value, but the right does not.

2. The name of the variable defined outside the function can be the same as the name of the formal parameter of the function definition;

pass by reference

The actual parameter will be assigned to the formal parameter when calling, so the actual method used is a simple value transfer; the result of the actual parameter is taken out and assigned to the formal parameter; Relationships are just the same as their results.

Sometimes, it is hoped that the external data obtained inside the function can be changed inside the function, then the function needs to be clearly informed, and the function will actively return the storage address of the data when it is called. This is pass by reference;

When calling, the actual parameter must be passed in by referring to the parameter position passed by value, and the parameter itself must be a variable (the variable can only point to the memory address of the data)

For example:

function display($a,&$b)
{
    //修改形参的值
    $a=$a*$a;
    $b=$b*$b;
    echo $a,'<br/>',$b,'<br/>';
}
$a=10;
$b=20;
display($a,$b);
echo '<hr/>',$a,'<br/>',$b;
?>

Note: When the formal parameter in the function is passed as the actual parameter of the variable reference, if it is not a variable, an error will be reported;

function body

Inside a function (i.e. all code inside curly braces)

Function body: Basically all code can be used as the function body of a function

function return value

Return value: return, refers to the demerit of the function implementation, and returns to the outside of the function (at the function call) through the return keyword: all functions in PHP have a return value, (if there is no clear use of return, then the system Returns NULL by default)

<?php
function display(){
    echo __FUNCTION__;//输出函数名
}
var_dump(display());
// ?>

 

<?php
function add($a1,$a2){
    return $a1+$a2;
}
$a3=add(10,11);
echo $a3
?>
运行结果:
21

Notice:

1. Return will directly end the function, so all statements after return will not be executed

2. return can also be used directly in the file (not in the function); it means that the file will hand over the content following the result return to the location containing the current file (usually used more in configuration system files)

scope

Scope: the area where a variable can be accessed

Since variables can be defined externally or inside functions; scopes are strictly divided into two types; but PHP itself also has a special scope, so there are three

1. Global variable: a variable defined by the user (defined outside the function)

It belongs to the global space; it is only allowed to be used in the global space in PHP; theoretically, it cannot be accessed inside the function (js can)

Script cycle: until the end of the script run

2. Local variables: variables defined inside the function

Belonging to the current function space: In PHP, it is only allowed to be used within the current function itself

Function cycle: the end of function execution;

3. Superglobal variables: system-defined variables (predefined variables);

The global space to which it belongs: no access restrictions (that is, both inside and outside the function can be accessed)

<?php
//PHP中作用域
$global ='global';
// 全局变量的定义
function display()
{
    $inner = __FUNCTION__;
    // 定义局部变量
    echo $global;
    // 尝试函数空间访问全局变量
    // 这里访问不到,因为全局变量不能在函数内部使用
}
 display();
 echo $global;
 //全局空间访问全局变量
?>

You can use arrays or parameter passing to realize local variables accessing global variables

In PHP, there is another way to realize that the global can access the local, and the local can also access the global; use the GLOBAL keyword

1. If the variable name defined using global exists externally (global variable), then the variable defined by the system inside the function directly points to the memory space pointed to by the external variable (the same variable)

2. If the variable name defined using global does not exist outside (global variable), then the system will automatically define a global variable with the same name as the local variable in the global space (outside the function)

Essence: Inside and outside the function, use the same block of memory address to save data for a variable with the same name, so as to achieve common ownership

<?php
//PHP中作用域
$global ='global';
// 全局变量的定义
function display()
{
    $inner = __FUNCTION__;
    // 定义局部变量
    global $global;
    //适应global关键字将外部的global引入到函数内部
    echo $global;
    // 尝试访问全局变量
    //这里正常输出
}
display();
?>

static variable

Static variable: static is a variable defined inside a function, which is used to share data across functions: all local variables will be cleared after the function runs, and if the function is re-run, all local variables will be re-initialized, static variables The function is to keep the variable the last result instead of clearing it.

For example:

<?php
function display()
{
    $local =1;
    static $count=1;
    $count+=1;
    $local+=1;
    echo '<hr/>';
    echo $count,'<br/>',$local,'<br/>';
}
display();
display();
display();
?>

The principle of static variables: the system will initialize the static line when compiling; assign values ​​to static variables;

Application scenario:

1. Statistics: count the number of times the current function is called

2. In order to coordinate the different results obtained by calling the function multiple times

variable function

Variable function: currently there is a variable that holds the value of a function name, then you can use variable + () to act as the function name

For example:

<?php
function display()
{
    echo __FUNCTION__;
}
$func='display';
echo $func,'<hr/>';
//使用可变函数(变量)访问函数
display();
// 使用函数名访问函数
?>

There are many variable functions in the process of using the system. When using many system functions, the user needs to define a custom function externally, but it needs to be passed into the system function for internal use.

Callback function: The process of passing a user-defined function to another function (function name) to use.

anonymous function

basic concept

function without name

Format:

variableName = function() {

//function body

}

For example:

<?php
$a=function()
{
 echo "hello world";
};
 $a();
?>

The anonymous function saved by the variable essentially gets an object (closure)

Closure

closure , the word comes from a combination of two; the block of code to be executed (these free variables and the objects they refer to are not freed because they are contained within the code block) and the computing environment that provides bindings for the free variables ( scope)

Simple understanding: there are some local variables (code blocks that need to be executed) inside the function that are not released after the function is executed, because there are corresponding functions inside the function that are referenced (internal functions of the function)

For example:

<?php
function display()
{
    $name= __FUNCTION__;
    $innerfunction=function() use($name)
    //use就是将外部的变传入内部进行使用 
    {
        //函数的内部的函数
        echo $name;
    }
}
display();
?>

There are several ways to detect that the local variables of the function are not released after they are used inside the function:

1. Use inner anonymous function

2. Anonymous function uses variable use

3. The anonymous function is returned to the outside

pseudo type

Pretend type: A type that does not actually exist in PHP, but the pseudo type can help programmers to better view the operation manual and learn more conveniently

MIXed: mixed, can be a variety of data types in PHP

Number: numeric, can be any numeric type (integer and floating point)

Library Functions

functions for output

print(): Similar to what the echo output provides, it is essentially a structure (not a function)

print_r(): Similar to var_dump, but simpler than var_dump, it will not output the data type, only the value.

For example:

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

function of time

date(): According to the specified corresponding timestamp (in seconds from 1970 Greenwich Mean Time), if no specific timestamp is specified, then the current timestamp is interpreted by default

time(): Returns the number of seconds since (January 1, 1970 00:00:00 GMT) to the current time.

microtime(): Get the timestamp at the microsecond level;

For example:

<?php
echo date('Y m d H:i:s',12345678),'<br/>';
echo time(),'<br/>';
echo microtime(),'<br/>';
?>

strtotime(): Convert a string to a timestamp according to the specified format

functions for numbers

max(): specifies the maximum value in the parameter

min(): specifies the minimum value among the parameters

rand(): Get a random number in a specified interval

mt_rand(): Same as rand, more efficient

round(): rounding

cell(): round up

floor(): round down

pow(): Find the result of the specified index of the specified number

abs(): absolute value

sqrt(): Find the square root

functions about functions

function_exists(): Determine whether the specified function name exists in memory (help users not to use a function that does not exist)

func_get_arg(): Get the parameter corresponding to the specified value in the custom function

func_get_args(): Get all parameters in the custom function

func_num_args(): the number of parameters in the current custom function

For example:

<?php
echo '<pre>';
function test($a,$b)
{
var_dump(func_get_arg(1));
//获取指定参数
var_dump(func_get_args());
//获取所有参数
var_dump(func_num_args());
//获取参数个数
}
function_exists('test') && test(1,'2,3,4');
// 判断是该函数否存在
?>

PHP error handling

Error handling: It means that when the system (or user) executes certain codes, if there is an error, it will notify the programmer in the form of error handling.

Misclassification

1) Syntax error: The code written by the user does not conform to the syntax specification of PHP. Syntax errors will cause the code to fail during compilation, so the code will not be executed (Parse error)

2) Runtime error: The code compiles successfully, but some errors (runtime error) may occur due to unsatisfied conditions during the execution of the code

3) Logical errors: programmers are not standardized enough when writing code, and some logical errors occur, resulting in normal execution of the code, but the desired result cannot be obtained

$a = 10;
If($a = 1){     //最常见把比较符号写成赋值符号
//执行代码   
}

error code

All error codes seen are defined as system constants in PHP (can be used directly)

(1) System error:

E_PARSE: compilation error, code will not execute

E_ERROR: fatal error, fatal error, which will cause the code to fail to continue executing correctly (the error location is broken)

E_WARNING: warning, warning error, will not affect code execution, but may get unexpected results

E_NOTICE: notice, notification error, will not affect code execution

(2) User errors: E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE

The error code that the user will use when using a custom error trigger (the system will not use it)

(3) Others: E_ALL, which represents all errors (usually used more often in error control), it is recommended to use during the development process (development environment)

All error constants (codes) starting with E are actually stored by one byte, and each error occupies a corresponding bit. If you want to control some errors, you can use bit operations to operate

Exclude notification level notice: E_ALL & ~E_NOTICE

Just warnings and notifications: E_WARNING | E_NOTICE

wrong trigger

Triggered 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 syntax errors and runtime errors in the code.

Human trigger: Know that some logic may go wrong, so use the corresponding judgment code to trigger the error prompt of the response

Trigger_error (error prompt):

Strictness can be controlled by the second parameter

Error display settings

Error display settings: which errors should be displayed and how

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

2. It can be set in the running PHP script: the level of configuration items defined in the script is higher than that of the configuration file (usually during development, it will be controlled and configured in the code)

Error_reporting(): Set the corresponding error display level

Ini_set('Configuration item in the configuration file', configuration value)

For example:

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 the user:

1. Unfriendly

2. Insecure: Mistakes will expose a lot of website information (path, file name)

Therefore, in the production environment, errors are generally not displayed (there are fewer errors), but it is impossible to avoid errors (not all problems will be found during the test). Background programmers to modify: need to save to the log file, need to set the corresponding error_log configuration item in the PHP configuration file or in the code (ini_set)

1. Enable the log function

2. Specify the path

Custom Error Handling

The simplest error handling: trigger_errors() function, this function is an error prompt when an error occurs, but this function will not prevent the system from reporting an error

The PHP system provides a mechanism for users to handle errors: the user defines an error handling function, and then adds the function to the error handling handle of the operating system, and then the system uses 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, the system has requirements

string definition

  1. single quoted string

  2. double quoted string

    The way of quotation marks is more suitable for strings that are relatively short or have no structural requirements

    If the content is too long, you can use the following two methods

    Structural definition:

  3. nowdoc strings: single-quoted strings without single quotes

  4. heredoc string double quoted string without double quotes

    For example:

    <?php
    $str1='hello';
    $str2="hello";
    $str3=<<<EOD
        hello
            world
    EOD;
    $str4=<<<'EOD'
        hello
            world
    EOD;
    var_dump($str1,'<hr/>',$str2,'<hr/>',$str3,'<hr/>',$str4);
    ?>*

string escape

Escape: In the general computer protocol, there are some letters defined in a specific way, and the system will handle them in a specific way; usually this way is to use the characteristics of backslash + letter:

PHP is also the same mode when recognizing quasi-one characters;

Common escape symbols commonly used in PHP

\':apostrophe

\":Double quotes

\r: carriage return (theoretically jump to the first position of the current line)

\n: new line

\t: tab key, four spaces

\$: Use $ as a variable symbol in PHP, here means the character '$' itself

The difference between single quotes and double quotes:

1. Single quotes can recognize '\', but double quotes can't recognize '\';

2. Double quotes can recognize $ symbols, index double quotes can parse variables, but single quotes cannot parse variables, and will only print as they are

Rules for identifying variables with double quotes:

1. The system of the variable itself can be distinguished from the following content: so the independence of the variable should be ensured, and the system should not be difficult to distinguish;

2. Use the variable professional identifier and add a set of braces {} to the variable

Rules for structurally defining string variables:

1. The upper boundary character cannot be followed by any content

2. The lower boundary character must be the top case

3. The lower boundary symbol can only be followed by a semicolon and cannot be followed by any content

4. Institutionalization defines that everything inside the string is the string itself

string length problem

strlen function: function to get the length of a string (in bytes)

For example:

<?php
header('Content-type:text/html;charset=ytf-8');
$str1='hello';
$str2="hello world";
echo strlen($str1),'<br/>',strlen($str2);
?>

 

The length problem of multi-byte strings: including the length of Chinese

Multibyte string extension module: mbstring extension

First, you need to load the mbstring extension of PHP;

Now you can use many functions extended in mbstring

String related functions

  1. conversion function

    str_split (string, string length): Divide the string according to the specified length to get an array

    implode (connection method, array): connect the elements in the array into a string according to a certain rule

    explode (split character, target string): split the string into an array according to a certain format

  2. Intercept function

    trim (string, [specified character]): It is used to remove two hundred years of spaces by default, but you can also specify the content to be removed, which is to remove the content on both sides according to the specified amount of wool loop: until you encounter one that is not the target until the string;

    ltrim(): remove the left

    rtrim(): remove the right

    substr (string, starting position, [length]): start intercepting the string at the specified position, and can intercept the string of the specified length

    strstr (string, matching character): starting from the specified position, and intercepting to the end (can be used to get the file extension)

  3. size conversion function

    strtolower: all lowercase

    strtoupper: all uppercase

    ucfist: capitalize the first letter

  4. lookup function

    strpos(): Finds the position of the first occurrence of a specified character in a string

    strrpos(): Determine the position of the last occurrence of the specified character in the string

  5. replace function

    str_replace (matching object, replacement character, string itself): replace part of the string in the target string

  6. format function

    printf(): formatted output data

    sprintf(): formatted output data

  7. other functions

    str_repeat(): Repeat a string N times

    str_shuffle(): Randomly shuffle a string

array

The concept of an array

Array: array, a combination of data, refers to storing a set of data (multiple) in a specified container, using a variable to point to the container, and then you can get all the data in the container at once through the variable.

array definition syntax

The system provides a variety of ways to define arrays in PHP:

1. Use the array keyword: the most commonly used

$variable = array(element1, element2, element3..);

2. You can use square brackets to wrap data:

$variable = [element1, element2...];

3. Invisible array definition: Add a square bracket to the variable, and the system will automatically become an array

$variable[] = value 1; //If no subscript is provided, it will be automatically generated by the system (numbers: start from 0)

$variable[subscript] = value; //The content in the square brackets is called the subscript key, which can be letters (words) or numbers, similar to the rules of variable naming

PHP array features

1) Integer subscript or string subscript can be used

If the array subscripts are all integers: index the array

If the array subscripts are all strings: associative array

2) Different subscripts can be mixed: mixed array

3) The order of the array elements is subject to the order in which they are placed, and has nothing to do with subscripts

4) The self-growth feature of the number subscript: it starts to grow automatically from 0, if a larger one appears manually in the middle, then the subsequent self-growth elements start from the maximum value +1

5) Automatic conversion of special value subscripts

Boolean values: true and false

Empty: NULL

6) There is no type limit for array elements in PHP

7) There is no length limit for array elements in PHP

Supplement: The array in PHP is very large data, so the storage location is the heap area, and a continuous memory is allocated for the current array.

Multidimensional Arrays

Multidimensional array: the elements in the array are arrays

Two-dimensional array

Two-dimensional array: All elements in the array are one-dimensional arrays

Multidimensional Arrays

The array element in the second dimension can continue to be an array, and there is no dimension limit in PHP (PHP does not have a two-dimensional array in essence)

However: it is not recommended to use arrays with more than three dimensions, which will increase the complexity of access and reduce access efficiency.

Alien array (irregular array)

Shaped array: The elements in the array are irregular, and there are ordinary basic variables and arrays.

In actual development, it is not commonly used, try to make the array elements regular (easy to access)

array traversal

The basic meaning of traversal

Array traversal: Access to ordinary array data is achieved through the subscripts of the array elements. If all the data in the array needs to be output in sequence, we need to use some simplified rules to achieve automatic subscript acquisition and output. array element.

$arr = array(0=>array(‘name’ => ‘Tom’),1=>array(‘name’ => ‘Jim’));  //二维数组
//访问一维元素:$arr[一维下标]
$arr[0];    //结果:array(‘name’ => ‘Tom’);
//访问二维元素:$arr[一维下标][二维下标
$arr[1][‘name’];    //Jim

Foreach traversal syntax

The basic syntax is as follows:

Foreach($数组变量 as [$下标 =>] $值){
•   //通过$下标访问元素的下标;通过$值访问元素的值
}

In general: if it is an associative array (alphabetic subscript), you need a subscript, if it is a numeric subscript, you can directly access the value

When defining data storage, usually two-dimensional arrays do not have two-dimensional key subscripts as numbers. Generally, one-dimensional is a number (meaningless), and two-dimensional is a string (database table field), so when performing When traversing, usually only one-dimensional traversal is required to obtain two-dimensional array elements, and then the two-dimensional array elements are accessed through subscripts.

Foreach traversal principle

The principle of Foreach traversal: the essence is that there is a pointer inside the array, the default is to point to the first element of the array element, foreach is to use the pointer to obtain data and move the pointer at the same time.

Foreach($arr as $k => $v){
•   //循环体

1. foreach will reset the pointer: let the pointer point to the first element;

2. Enter the foreach loop: get the current first element through the pointer, then take out the subscript and put it in the corresponding subscript variable $k (if it exists), take out the value and put it in the corresponding value variable $v;( pointer down)

3. Enter the inside of the loop (loop body) and start executing;

4. Repeat 2 and 3 until the pointer cannot get the content at 2 (the pointer points to the end of the array)

For loop through the array

For loop: based on known boundary conditions (start and end) and then conditional changes (laws)

Therefore: the for loop traverses the array with corresponding conditions

1. Get the length of the array: count (array) to get the length of the array elements

2. The subscripts of array elements are required to be regular numbers

Array-related functions:

(1) Sorting function: Sorting the array elements is compared according to the ASCII code, and English comparison can be performed

sort(): order sorting (subscript rearrangement)

rsort(): sort in reverse order

asort(): sequential sorting (subscript reserved)

arsort(): sort in reverse order

ksort(): order sorting: according to the key name (subscript)

krsort(): sort in reverse order

shuffle(): Randomly shuffle the array elements, and the array subscripts will be rearranged

(2) Pointer function

reset(): Reset the pointer and return the array pointer to the first position

end(): Reset the pointer, pointing the array pointer to the last element

next(): Move the pointer down to get the value of the next element

prev(): Move the pointer up to get the value of the previous element

current(): Get the element value corresponding to the current pointer

key(): Get the subscript value corresponding to the current pointer

Note: next and prev will move the pointer, which may cause the pointer to move to the front or the end (leave the array), resulting in the array being unusable, and the actual pointer position cannot be returned through next and prev. The pointer can only be reset by end or reset

(3) Other functions

count(): counts the number of elements in the array

array_push(): Add an element to the array (behind the array)

array_pop(): Take an element from the array (behind the array)

array_shift(): Take an element from the array (in front of the array)

array_unshift(): add an element from the array (in front of the array)

array_reverse(): The array elements are reversed

in_array(): Determine whether an element exists in the array

array_keys(): Get all the subscripts of an array and return an index array

array_values(): Get all the values ​​of an array and return an index array

Guess you like

Origin blog.csdn.net/qq_68163788/article/details/131445295