In this article, we mainly share with you PHP error-prone notes - process control, functions, hoping to help everyone.
PHP provides some alternative syntax for flow control, including if
, while
, for
, foreach
and switch
. The basic form of the alternative syntax is to replace the left curly brace ({) with a colon (:), and replace the right curly brace (}) with endif;, endwhile;, endfor;, endforeach; and endswitch; respectively.
Note: Mixing the two syntaxes within the same control block is not supported.
Special Note: Any output (including spaces) between
switch
and the first case
will result in Grammatical errors. For example, this is invalid:
<?php switch ($foo): ?> <?php case 1: ?> ... <?php endswitch ?>
but this is valid because the newline character after switch
is considered part of the closing tag ?>
, so There cannot be any output between switch
and case
:
<?php switch ($foo): ?> <?php case 1: ?> ... <?php endswitch ?>
Note: It must be noted that elseif and else if They are considered identical only if curly braces are used. If you use a colon to define an if/elseif condition, you cannot use a two-word else if, otherwise PHP will generate a parsing error.
<?php /* 不正确的使用方法: */ if($a > $b): echo $a." is greater than ".$b; else if($a == $b): // 将无法编译 echo "The above line causes a parse error."; endif; /* 正确的使用方法: */ if($a > $b): echo $a." is greater than ".$b; elseif($a == $b): // 注意使用了一个单词的 elseif echo $a." equals ".$b; else: echo $a." is neither greater than or equal to ".$b; endif; ?>
for
Loops are the most complex loop structures in PHP. Its behavior is similar to that of C language. for
The syntax of the loop is:
for (expr1; expr2; expr3) statement
The first expression (expr1
) is unconditionally evaluated (and executed) once before the loop starts.
expr2
Evaluates before the start of each loop. If the value is TRUE, the loop continues and the nested loop statement is executed. If the value is FALSE, the loop is terminated.
expr3
is evaluated (and executed) after each loop.
Each expression can be empty or include multiple expressions separated by commas.
In the expression expr2
, all expressions separated by commas will be evaluated, but only the last result will be taken. expr2
Empty means that the loop will continue indefinitely (like C, PHP implicitly considers its value to be TRUE). This may not be as useless as you think, since you often want to end a loop with a conditional break statement rather than truth-checking a for expression.
Consider the following examples, they all display the numbers 1 to 10:
/* example 2 */ for ($i = 1; ; $i++) { if ($i > 10) { break; } echo $i; } /* example 3 */ $i = 1; for (;;) { if ($i > 10) { break; } echo $i; $i++; } /* example 4 */ for ($i = 1, $j = 0; $i <= 10; $j += $i, print $i, $i++); /* example */ $people = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; for($i = 0, $size = count($people); $i < $size; ++$i) { print $people[$i]; }
Can be used in excel:
<?php for($col = 'R'; $col != 'AD'; $col++) { echo $col.' '; } //returns: R S T U V W X Y Z AA AB AC //Take note that you can't use $col < 'AD'. It only works with != //Very convenient when working with excel columns. ?>
Add before $value Use&
to modify the elements of the array. This method willreference assignment
instead of copying a value (Remember to unset() the variable at the end, otherwise some unexpected results may occur).
<?php $arr = array(1, 2, 3, 4); foreach ($arr as &$value) { $value = $value * 2; } // $arr is now array(2, 4, 6, 8) unset($value); // 最后取消掉引用 ?>
The following code functions are exactly the same:
<?php $arr = array("one", "two", "three"); reset($arr); while (list(, $value) = each($arr)) { echo "Value: $value<br>\n"; } foreach ($arr as $value) { echo "Value: $value<br />\n"; } ?>
The following code functions are also exactly the same:
<?php $arr = array("one", "two", "three"); reset($arr); while (list($key, $value) = each($arr)) { echo "Key: $key; Value: $value<br />\n"; } foreach ($arr as $key => $value) { echo "Key: $key; Value: $value<br />\n"; } ?>
Use list()
to nested arrays Unpacking
(PHP 5 >= 5.5.0, PHP 7)
PHP 5.5 adds the ability to iterate over an array of arrays and unpack nested arrays into loop variables, just Provide list()
as a value.
<?php $array = [ [1, 2], [3, 4], ]; foreach ($array as list($a, $b)) { // $a contains the first element of the nested array, // and $b contains the second element. echo "A: $a; B: $b\n"; } ?>
The above routine will output:
A: 1; B: 2 A: 3; B: 4
break ends the current for
, foreach
, while Execution of
, do-while
or switch
structures.
break can accept an optional numeric parameter to determine how many loops to break out of.
<?php $i = 0; while (++$i) { switch ($i) { case 5: echo "At 5<br />\n"; break 1; /* 只退出 switch. */ case 10: echo "At 10; quitting<br />\n"; break 2; /* 退出 switch 和 while 循环 */ default: break; } } ?>
Version | Description |
---|---|
break 0; is no longer legal. This was interpreted as break 1; in previous versions. | |
Cancel passing variables as parameters (e.g. $num = 2; break $num;). |
breakwill only show "hello"continuestatement that is in the outer part of a program (e.g. not in a control loop) will end the script.
<?php echo "hello"; if (true) break; echo " world"; ?>Copy after login
continue is used in the loop structure to skip the remaining code in this loop and evaluate the condition as When true, start executing the next cycle.
Note:
Note that in PHP the switch statement is considered a loop structure that can use continue.
<?php $i = 0; while ($i++ < 5) { echo "Outer<br />\n"; while (1) { echo "Middle<br />\n"; while (1) { echo "Inner<br />\n"; continue 3; } echo "This never gets output.<br />\n"; } echo "Neither does this.<br />\n"; } ?>Copy after login
Description | ||
---|---|---|
continue 0; is no longer legal. This was interpreted as continue 1; in previous versions. | ||
Cancel passing variables as parameters (e.g. $num = 2; continue $num;). |
Type | Description | Minimum PHP version |
---|---|---|
Class/interface name |
The parameter must be an instanceof the given class or interface name. | PHP 5.0.0 |
self |
The parameter must be an instanceof the same class as the one the method is defined on. This can only be used on class and instance methods. | PHP 5.0.0 |
array |
The parameter must be an array. | PHP 5.1.0 |
callable |
The parameter must be a valid callable. | PHP 5.4.0 |
bool |
The parameter must be a boolean value. | PHP 7.0.0 |
float |
The parameter must be a floating point number. | PHP 7.0.0 |
int |
The parameter must be an integer. | PHP 7.0.0 |
string |
The parameter must be a string. | PHP 7.0.0 |
注意:类型提示只能是以上表格中的类型(单词),例如bool
不能写作boolean
(boolean会被当作class或interface解析)。
类型提示:
<?php function test(boolean $param) {} test(true); ?>
以上例程会输出:
Fatal error: Uncaught TypeError: Argument 1 passed to test() must be an instance of boolean, boolean given, called in - on line 1 and defined in -:1
严格类型:使用 declare
语句和strict_types
声明来启用严格模式(如declare(strict_types=1);
)。
可变数量的参数列表:
PHP 在用户自定义函数中支持可变数量的参数列表。在 PHP 5.6 及以上的版本中,由 ...
语法实现(类似于js);在 PHP 5.5 及更早版本中,使用函数 func_num_args(),func_get_arg(),和 func_get_args() 。
...
既可以用于定义可变参数列表,也可以用来提供参数解包
Example #13 使用 ...
定义可变参数 in PHP 5.6+
<?php function sum(...$numbers) { $acc = 0; foreach ($numbers as $n) { $acc += $n; } return $acc; } echo sum(1, 2, 3, 4);//10 ?>
Example #14 使用 ...
提供参数
<?php function add($a, $b) { return $a + $b; } echo add(...[1, 2])."\n";//3 $a = [1, 2]; echo add(...$a);//3 ?>
Example #15 部分可变参数以及可变参数列表的类型提示
<?php function total_intervals($unit, DateInterval ...$intervals) { $time = 0; foreach ($intervals as $interval) { $time += $interval->$unit; } return $time; } $a = new DateInterval('P1D'); $b = new DateInterval('P2D'); echo total_intervals('d', $a, $b).' days';//3 days // This will fail, since null isn't a DateInterval object. echo total_intervals('d', null); //Catchable fatal error: Argument 2 passed to total_intervals() must be an instance of DateInterval, null given, called in - on line 14 and defined in - on line 2 ?>
在php 5.5以及之前版本中使用可变参数:
<?php function sum() { $acc = 0; foreach (func_get_args() as $n) { $acc += $n; } return $acc; } echo sum(1, 2, 3, 4);//10 ?>
如果省略了 return,则返回值为 NULL。
Example #1 return 的使用
<?php function square($num) { $sum = $num * $num; } function square2($num) { $sum = $num * $num; return; } var_dump(square(4)); // NULL var_dump(square2(4)); // NULL ?>
从函数返回一个引用,必须在函数声明和指派返回值给一个变量时都使用引用运算符 &
:
Example #3 从函数返回一个引用
<?php function &returns_reference() { return $someref; } $newref =& returns_reference(); ?>
PHP 支持可变函数的概念。这意味着如果一个变量名后有圆括号,PHP 将寻找与变量的值同名的函数,并且尝试执行它。可变函数可以用来实现包括回调函数,函数表在内的一些用途。
可变函数不能用于例如 echo
,print
,unset()
,isset()
,empty()
,include
,require
以及类似的语言结构。需要使用自己的包装函数来将这些结构用作可变函数。
当调用静态方法时,函数调用要比静态属性优先
Example #3 Variable 方法和静态属性示例
<?php class Foo { static $variable = 'static property'; static function Variable() { echo 'Method Variable called'; } } echo Foo::$variable; // This prints 'static property'. It does need a $variable in this scope. $variable = "Variable"; Foo::$variable(); // This calls $foo->Variable() reading $variable in this scope. ?>
As of PHP 5.4.0, you can call any callable stored in a variable.
Example #4 Complex callables
<?php class Foo { static function bar() { echo "bar\n"; } function baz() { echo "baz\n"; } } $func = array("Foo", "bar"); $func(); // prints "bar" $func = array(new Foo, "baz"); $func(); // prints "baz" $func = "Foo::bar"; $func(); // prints "bar" as of PHP 7.0.0; prior, it raised a fatal error ?>
匿名函数(Anonymous functions)
,也叫闭包函数(closures)
,允许 临时创建一个没有指定名称的函数。最经常用作回调函数(callback)参数的值。当然,也有其它应用的情况。
匿名函数目前是通过 Closure
类来实现的。
闭包可以从父作用域中继承变量。 任何此类变量都应该用 use
语言结构传递进去。 PHP 7.1 起,不能传入此类变量: superglobals、 $this 或者和参数重名。
Example #3 从父作用域继承变量(传值
和传引用
)
<?php $message = 'hello'; // 没有 "use" $example = function () { var_dump($message); }; echo $example(); //Notice: Undefined variable: message in /example.php on line 6 //NULL // 继承 $message $example = function () use ($message) { var_dump($message); }; echo $example();//string(5) "hello" $message = 'world'; echo $example();//string(5) "hello" // Reset message $message = 'hello'; $example = function () use (&$message) { var_dump($message); }; echo $example();//string(5) "hello" $message = 'world'; echo $example();//string(5) "world" // Closures can also accept regular arguments $example = function ($arg) use ($message) { var_dump($arg . ' ' . $message); }; $example("hello");//string(11) "hello world" ?>
闭包中 $this
的绑定:
<?php class Test { public function testing() { return function() { var_dump($this); }; } public function testing2() { return static function() { var_dump($this); }; } } $object = new Test; $function = $object->testing(); $function(); $object->testing2()(); ?>
以上例程会输出(PHP 5.4+):
object(Test)#1 (0) { } PHP Notice: Undefined variable: this in D:\php\test\test.php on line 13 Notice: Undefined variable: this in D:\php\test\test.php on line 13 NULL
而在PHP 5.3中:
PHP Notice: Undefined variable: this in D:\php\test\test.php on line 7 Notice: Undefined variable: this in D:\php\test\test.php on line 7 NULL PHP Parse error: syntax error, unexpected T_FUNCTION, expecting T_PAAMAYIM_NEKUDOTAYIM in D:\php\test\test.php on line 12 Parse error: syntax error, unexpected T_FUNCTION, expecting T_PAAMAYIM_NEKUDOTAYIM in D:\php\test\test.php on line 12
Note: 可以在闭包中使用 func_num_args(),func_get_arg() 和 func_get_args()。
call_user_func_array — 调用回调函数,并把一个数组参数作为回调函数的参数
call_user_func — 把第一个参数作为回调函数调用
create_function — Create an anonymous (lambda-style) function
forward_static_call_array — Call a static method and pass the arguments as array
forward_static_call — Call a static method
func_get_arg — 返回参数列表的某一项
func_get_args — 返回一个包含函数参数列表的数组
func_num_args — Returns the number of arguments passed to the function
function_exists — 如果给定的函数已经被定义就返回 TRUE
get_defined_functions — 返回所有已定义函数的数组
register_shutdown_function — 注册一个会在php中止时执行的函数
register_tick_function — Register a function for execution on each tick
unregister_tick_function — De-register a function for execution on each tick
相关推荐:
Detailed explanation of javascript asynchronous execution and operation flow control examples
The above is the detailed content of PHP process control function error-prone note sharing. For more information, please follow other related articles on the PHP Chinese website!