Home php教程 php手册 php基础知识:控制结构

php基础知识:控制结构

Jun 13, 2016 pm 12:35 PM
java php mainstream and basic knowledge control of structure language

php的控制结构,大部分和其他主流语言,如C,Java等相同。

这里列出一些不同的以及经常被考到的细节:

1>流程控制的替代语法(pascal的风格)
主要用在if,while,for,foreach 和 switch语句中。替代语法的基本形式是把左花括号({)换成冒号(:),把右花括号(})分别换成 endif;,endwhile;,endfor;,endforeach; 以及 endswitch;。 
例(1):
if ($a == 5):
 /*dosomething1*/
 /*dosomething1*/
endif;
就等同于:
if ($a == 5){
 /*dosomething1*/
 /*dosomething1*/
}
例(2):
if ($a == 5):
   echo "a equals 5";
   echo "...";
elseif ($a == 6):
   echo "a equals 6";
   echo "!!!";
else:
   echo "a is neither 5 nor 6";
endif;

2>for语句(经常考,并且彻底的明白也是必要的).
格式:(支持`:`……`endfor;`代替{}的形式)
for (expr1; expr2; expr3)
   statement
运行过程:
第一个表达式(expr1)在循环开始前无条件求值一次。 
expr2 在每次循环开始前求值。如果值为 TRUE,则继续循环,执行嵌套的循环语句。如果值为 FALSE,则终止循环。 
expr3 在每次循环之后被求值(执行)。 
等同的while语句为:
expr1;
while(expr2):
   expr3;
endwhile;

3>break的不同。
break的作用是:结束当前 for,foreach,while,do-while 或者 switch 结构的执行。
同时break后面可以跟一个数字来决定跳出几层循环。break 1;为跳出1层循环。
我不知道c里面有没有,因为我没有c语言的系统的书。

4>foreach
格式:
a.foreach (array_expression as $value)
   statement
b.foreach (array_expression as $key => $value)
   statement
说明:
a格式遍历给定的 array_expression 数组。每次循环中,当前单元的值被赋给 $value 并且数组内部的指针向前移一步(因此下一次循环中将会得到下一个单元)。 
b格式做同样的事,只除了当前单元的键名也会在每次循环中被赋给变量 $key。

注意:
a.当 foreach 开始执行时,数组内部的指针会自动指向第一个单元。这意味着不需要在 foreach 循环之前调用 reset()。/*reset(array &array):把array的内部指针移动到数组array的第一个单元并返回值*/ 
b.除非数组是被引用,foreach 所操作的是指定数组的一个拷贝,而不是该数组本身。因此数组指针不会被 each() 结构改变,对返回的数组单元的修改也不会影响原数组。不过原数组的内部指针的确在处理数组的过程中向前移动了。假定 foreach 循环运行到结束,原数组的内部指针将指向数组的结尾。 
自 PHP 5 起,可以很容易地通过在 $value 之前加上 & 来修改数组的单元。此方法将以引用赋值而不是拷贝一个值。
例:
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
   $value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
c.foreach 不支持用“@”来抑制错误信息的能力。

使用foreach例子:
$arr = array("one", "two", "three");
reset($arr);
while (list(, $value) = each($arr)) {
   echo "Value: $value
\n";
}
foreach ($arr as $value) {
   echo "Value: $value
\n";
}

5>continue的不同(我很少用continue)
作用:在循环结构用用来跳过本次循环中剩余的代码并在条件求值为真时开始执行下一次循环。
同break一样,也接受一个数字来决定跳出几层到循环代码尾部。
注明:continue;和continue 1;一样,都是跳到本层本次循环的末尾。continue 2则跳出本层循环到外层的末尾。

6>switch中continue的作用:类似于break(和其他语言不同)。

7>declare 
结构用来设定一段代码的执行指令。declare 的语法和其它流程控制结构相似: 
declare (directive)
   statement
directive 部分允许设定 declare 代码段的行为。目前只认识一个指令:ticks(更多信息见下面 ticks 指令)。 
declare 代码段中的 statement 部分将被执行  怎样执行以及执行中有什么副作用出现取决于 directive 中设定的指令。 
declare 结构也可用于全局范围,影响到其后的所有代码。

主要的例子就是用于Tricks(目前也只有tricks):
例如:
function profile($dump = FALSE)
{
   static $profile;
  // Return the times stored in profile, then erase it
   if ($dump) {
       $temp = $profile;
       unset($profile);
       return ($temp);
   }
   $profile[] = microtime();
}
// 注册函数profile为ticks函数
register_tick_function("profile");
// 初始化。
profile();
// 运行一块代码,当执行2句(ticks=2)简单语句时,就调用一次函数profile();
declare(ticks=2) {
   for ($x = 1; $x        echo similar_text(md5($x), md5($x*$x)), "
;";
   }
}
// 展示存放在概况存储区(profile)的数据
print_r(profile (TRUE));

注意:
register_tick_function() should not be used with threaded webserver modules. Ticks are not working in ZTS mode and may crash your webserver. 
不能用在多道处理模块(??不明白??什么是多道处理模块?)的服务器上,不然会crash。我crash好多次了。郁闷。

8>require和include
不同点:
include() 产生一个警告而 require() 则导致一个致命错误。换句话说,如果想在遇到丢失文件时停止处理页面就用 require()。include() 就不是这样,脚本会继续运行。同时也要确认设置了合适的 include_path。注意在 PHP 4.3.5 之前,包含文件中的语法错误不会导致程序停止,但从此版本之后会。

相同点以及用法:
a.变量范围:
当一个文件被包含时,其中所包含的代码继承了 "包含语句" 所在行的变量范围。从该处开始,调用文件在该行处可用的任何变量在被调用的文件中也都可用。不过所有在包含文件中定义的函数和类都具有全局作用域。 
如果 "包含语句" 出现于调用文件中的一个函数里,则被调用的文件中所包含的所有代码将表现得如同它们是在该函数内部定义的一样。所以它将遵循该函数的变量范围。

b.解析模式
当一个文件被包含时,语法解析器在目标文件的开头脱离 PHP 模式并进入 HTML 模式,到文件结尾处恢复。由于此原因,目标文件中应被当作 PHP 代码执行的任何代码都必须被包括在有效的 PHP 起始和结束标记之中。 

c.在条件语句中的格式问题
因为 include() 和 require() 是特殊的语言结构,在条件语句中使用必须将其放在语句组中(花括号中)。
因为 include() 是一个特殊的语言结构,其参数不需要括号。在比较其返回值时要注意。

d.处理返回值
可以在被包括的文件中使用 return() 语句来终止该文件中程序的执行并返回调用它的脚本。同样也可以从被包含的文件中返回值。可以像普通函数一样获得 include 调用的返回值。不过这在包含远程文件时却不行,除非远程文件的输出具有合法的 PHP 开始和结束标记(如同任何本地文件一样)。可以在标记内定义所需的变量,该变量在文件被包含的位置之后就可用了。
例子:
return.php
==============
$var = 'PHP';
return $var;

noreturn.php
==============
$var = 'PHP';

testreturns.php
=============================
$foo = include 'return.php';
echo $foo; // prints 'PHP'
$bar = include 'noreturn.php';
echo $bar; // prints 1

e.函数和变量重定义的问题.
为了防止这种现象出现,可以使用include_once或者require_once

f.其它:
在 PHP 4.0.2 之前适用以下规则:require() 总是会尝试读取目标文件,即使它所在的行根本就不会执行。条件语句不会影响 require()。不过如果 require() 所在的行没有执行,则目标文件中的代码也不会执行。同样,循环结构也不影响 require() 的行为。尽管目标文件中包含的代码仍然是循环的主体,但 require() 本身只会运行一次

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

See all articles