Home > Article > Backend Development > Process Control - PHP Manual Notes
Scripts are composed of statements, and statements rely on process control to implement functions. This section mainly introduces the use of several keywords.
elseif
elseif
and else if
behave exactly the same. If you use a colon to define the if/elseif
condition, you cannot use the two-word else if
, otherwise PHP will generate a parsing error.
<code><?php $a = 1; $b = 2; if($a > $b) : echo "$a is greater than $b"; elseif($a == $b) : echo "$a equals $b"; else : echo "$a is neither greater than or equal to $b"; endif;</code>
Alternative syntax
The following keywords can use the alternative syntax of flow control. The basic form is to replace the left curly brace with a colon and the right curly brace with the following characters.
<code>if - endif while - endwhile for - endfor foreach - endforeach switch - endswitch</code>
Attention! PHP does not support mixing the two syntaxes within the same control block.
do-while
This loop looks familiar at first glance, but some of its uses are overlooked.
The manual says that experienced C language users may be familiar with a different do-while
loop usage, which puts the statement inside do-while(0)
. This is the first time I have heard of this technique. It seems that I am still a novice in C language.
By the way, let’s search and sort out the benefits of this special usage of do-while(0)
.
break
to skip the remaining section of code. goto
statement. This post explains very well, the role of do{}while(0) - c++ - SegmentFault.
foreach
foreach
can only be applied to array and object traversal. The foreach
syntax structure provides a simple way to traverse an array. There are two syntaxes below.
<code>foreach(array_expression as $value) statement foreach(array_expression as $key => $value) statement</code>
To modify the value of an array element, you need to use reference assignment, which is achieved by adding &
before $value
.
<code><?php $arr = array(1, 2, 3, 4); foreach($arr as &$value) { $value = $value * 2; } unset($value); foreach($arr as $value) { echo "$value "; // 2 4 6 8 }</code>
Attention! The $value
reference of the last element of the array will still be retained after the foreach
loop. It is recommended to use unset()
to destroy it.
list-each
In the sample program, a special traversal method was also found, tentatively called list-each
.
When foreach
starts executing, the pointer inside the array will automatically point to the first unit, so there is no need to call reset()
before the foreach
loop. But for list-each
in while
, the array internal pointer $arr
will always exist, so reset($arr)
is needed before the next loop.
<code><?php $arr = array('one', 'two', 'three'); // reset($arr); while(list($key, $value) = each($arr)) { echo "Key: $key; Value: $value "; } reset($arr); while(list($key, $value) = each($arr)) { echo "Key: $key; Value: $value "; }</code>
In the above code, the first reset
can be omitted, but the second reset
cannot be omitted.
list
PHP 5.5 adds the ability to iterate over an array of arrays and unpack nested arrays into loop variables.
<code><?php $array = [ [1, 2], [3, 4], ]; foreach($array as list($a, $b)) { echo "A: $a; B: $b"; }</code>The number of cells in
list()
can be less than that of the nested array, in which case the extra array cells will be ignored. If more, an error message will be issued.
break
break
is used to end the execution of the current for/foreach/while/do-while/switch
structure. break
can accept an optional numeric parameter to decide how many loops to break out of, but the parameter cannot be a variable.
break
This is the first time I encountered breaking out of multiple loops, so I wrote a small program to try it out.
<code><?php while(1) { while(1) { echo 'hello '; break 2; } } echo 'world';</code>
I specially tried it in C language and got a syntax error.
continue
Similar to break
, continue
can also accept an optional numeric parameter to determine how many loops to skip to the end of the loop.
Attention! In PHP, the switch
statement is considered a loop structure that can use continue
.
switch
The manual says that PHP is different from other languages. The continue
statement acting on switch
is similar to break
. What does it mean?
switch/case
does a loose comparison ==
instead of a strict comparison ===
. In terms of efficiency, the condition in the switch
statement is only evaluated once and used to compare with each case
statement. case
Expression can be any expression that evaluates to a simple type, arrays or objects cannot be used. It is allowed to use a semicolon instead of a colon after a case
statement.
declare
Thedeclare
structure is used to set the execution instructions of a piece of code. The syntax structure is as follows:
<code>declare(directive) statement</code>The
directive
section allows you to set the behavior of declare
code segments. Currently, only two commands are recognized: ticks
and encoding
. The declare
structure can also be used in global scope, affecting all code after expiration. But if a file with a declare
structure is included by other files, it will not work on the parent file that contains it.
Tick (clock cycle) is an event that occurs every time the interpreter executes N timeable low-level statements in the declare
code segment. The events that occur in each tick are specified by register_tick_function()
. The usage is roughly as follows.
<code>declare(ticks = 1); function tick_handler() { echo "tick_hander() called.\n"; } register_tick_function('tick_hander');</code>
可计时的低级语句有很多,register_tick_function()
后会调用一次周期事件,每条语句后会调用一次周期事件,花括号结束时会调用一次周期事件。
注意,PHP中表达式不能用逗号隔开,不然会出现语法错误。这点与C语言不同,刚注意到。
可以用encoding指令来对每段脚本指定其编码方式。用法如下:
<code>declare(encoding = 'ISO-8859-1);</code>
return
如果是在全局范围中调用,则当前脚本文件中止运行。如果当前脚本文件是被include
或者require
,则控制交回调用文件。如果当前脚本时被include
的,则return
的值会被当作include
调用的返回值,那require
呢?
require
require
和include
几乎完全一样,除了处理失败的方式不同之外。
require
在出错时产生E_COMPILE_ERROR
级别的错误,脚本中止。而include
只产生警告E_WARNING
,脚本继续执行。
include
include
语句包含并运行指定文件,这里要注意一下指定文件的寻找次序。
include_path
会被完全忽略。include_path
指定的目录寻找。若没找到才在调用脚本文件所在目录和当前工作目录下寻找。那么问题来了,调用脚本文件所在目录和当前工作目录有什么区别呢?include
结构会发出一条警告,require
结构会发出一个致命错误。当一个文件被包含时,其中包含的代码继承了include
所在行的变量范围。从该处开始,被调用文件中定义的变量才可在调用文件中使用。当一个文件被包含时,语法解析器在目标文件的开头脱离PHP模式并进入HTML模式,当文件结尾回复。
对于返回值,在失败时include
返回FALSE
并且发出警告。成功的包含则返回1,除非在包含文件中另外给出了返回值。如果在包含文件中定义有函数,这些函数不管是在return
之前还是之后定义的,都可以独立在主文件中使用。
如果来自远程服务器的文件应该在远端运行而只输出结果,那用readfile()
函数更好。另一种将PHP文件包含到一个变量中的方法是用输出控制函数结合include
来捕获其输出。第一次遇到,比较陌生。下面这段代码能将脚本vars.php
中返回的内容输出。
<code><?php $string = get_include_contents('vars.php'); function get_include_contents($filename) { if(is_file($filename)) { ob_start(); include $filename; $contents = ob_get_contents(); ob_end_clean(); return $contents; } return false; } echo $string;</code>
因为include
和require
是一种特殊的语言结构,其参数不需要括号。如果文件被包含两次,PHP会发出致命错误,因为函数已经被定义。推荐使用include_once
。
require_once
require_once
语句和require
语句完全相同,唯一区别是,PHP会检查该文件是否已经被包含过,如果是则不会再次包含。
include_once
include_once
语句和include
语句类似,唯一区别是如果该文件已经被包含过,则不会再次包含。
goto
goto
操作符用于跳转到程序的另一位置,目标位置可以用目标名称加上冒号来标记。PHP中的goto
有一定限制,目标位置只能位于同一个文件和作用域。也就是说无法跳出一个函数或类方法,也无法跳入到任何循环或者switch
结构。
(全文完)
以上就介绍了流程控制 - PHP手册笔记,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。