php语法基础

一,概述

二,PHP脚本标记

1、 PHP脚本有四种标记: 短标签和asp标签虽方便但移植性及发行性较差,通常不推荐。此外注意如果将 PHP 嵌入到 XML 或 XHTML 中则需要使用标准标签 <?php ?> 以保持符合标准。

A, 标准标签:<?php .. ?>

B, 脚本标签:<script language=”php”>…</script>

C, 短标签:<? … ?> 需要在php.ini中设置short _open_tag=on,默认是on,或者在 PHP 编译时加入了 –enable-short-tags 选项。(PHP 3版本还可以通过 short_tags() 函数激活使用短标记。)

D, asp标签(PHP 3.0.4 版后支持): <% … %>需要在php.ini中设置asp_tags=on,默认是off

2, 指令分隔符: 同 C,java 或 Perl 一样,PHP 需要在每个语句除末行(因为结束标记隐含表示了一个分号 )后用分号结束指令。而文件末行省略分号有利于使用输出缓冲和 include() 或者 require()

3, 注释: PHP 支持 C,C++ 和 Unix Shell 风格(Perl 风格)的注释。例如:

单行注释:// ,# 多行注释:/* */ <?php echo "This is a test"; // 单行注释 (c++ 风格), /* 多行注释:单行注释说明1:"// ?>"中 ?>有效, 单行注释说明2:"// </script>"中 </script>无效 */ echo "This is yet another test"; echo "One Final Test"; # 单行注释 (shell风格) ?>

三,PHP数据类型

1, 基本数据类型:Integer,Double,String,Boolean,Object(对象或类),Array(数组)

A, 四种标量类型:

(1), boolean(布尔型) :布尔值 FALSE情况是:整型0,浮点0.0,空白字符串和字符串 “0”,没有成员变量的数组,没有单元的对象(仅适用于 PHP 4),特殊类型 NULL(包括尚未设定的变量)。其它值都被认为是 TRUE(包括任何资源)

(2), integer(整型):八进制前缀0,十六进制前缀0x,如果向八进制数如01090传递了一个非法数字(即 8 或 9),则后面其余数字会被忽略,等于010。

(3), float(浮点型,也作double,浮点数,双精度数或实数):浮点数精度是不准确的

(4), string(字符串):

B, 两种复合类型:

(1), array(数组) :PHP 中的数组实际上是把一个优化过的有序图类型当成数组来使用。 应该始终在用字符串(除常量或变量)表示的数组索引上加上引号。

定义 array():

array( [key =>] // key 可以是 integer 或者 string value // value 可以是任何值 , ... ) <?php $arr = array("foo" => "bar", 12 => true); //key如果是浮点数则取整为integer echo $arr["foo"]; // bar echo $arr[12]; // 1 ?>

缺省的键名取当前最大的整数索引值,而新的键名索引为当前最大索引加一。如果指定的键名已经有了值,则该值会被覆盖。 自 PHP 4.3.0 起,上述的索引生成方法改变了。如今如果给一个当前最大键名是负值的数组添加一个新值,则新生成的的索引将为零(0)。以前新生成的索引为当前最大索引加一,和正值的索引相同。

添加/修改数组元素:

<?php $arr = array(5 => 1, 12 => 2); $arr[] = 56; // This is the same as $arr[13] = 56; // at this point of the script $arr["x"] = 42; // This adds a new element to // the array with key "x" unset($arr[5]); // This removes the element from the array unset($arr); // This deletes the whole array ?>

(2), object(对象)

对象初始化:要初始化一个对象,用 new 语句将对象实例到一个变量中。

<?php class foo { function do_foo() { echo "Doing foo."; } } $bar = new foo; $bar->do_foo(); ?>

转换为对象:如果将一个对象转换成对象,它将不会有任何变化。如果其它任何类型的值被转换成对象,内置类 stdClass 的一个实例将被建立。如果该值为 NULL,则新的实例为空。对于任何其它的值,名为 scalar 的成员变量将包含该值。

<?php $obj = (object) 'ciao'; echo $obj->scalar; // outputs 'ciao' ?>

C, 特殊数据类型:

(1), Resourse(对第三方资源(如数据库)的引用,PHP 4 引进):资源是一种特殊变量,保存了到外部资源的一个引用。资源是通过专门的函数来建立和使用的。

禁止类型转换为资源:由于资源类型变量保存有为打开文件、数据库连接、图形画布区域等的特殊句柄,因此无法将其它类型的值转换为资源。

释放资源:由于 PHP4 Zend 引擎引进了资源计数系统,可以自动检测到一个资源不再被引用了(和 Java 一样)。这种情况下此资源使用的所有外部资源都(除了持久数据库连接)会被垃圾回收系统释放。由此原因,很少需要用某些 free-result 函数来手工释放内存。

(2), Null(空,未初始化的变量,PHP4引进):特殊的 NULL 值表示一个变量没有值。NULL 类型唯一可能的值就是 NULL。 在下列情况下一个变量被认为是 NULL:被赋值为 NULL,尚未被赋值, 被 unset()。

语法:NULL 类型只有一个值,就是大小写敏感的关键字 NULL。

<?php $var = NULL; ?>

D, 伪类型:

(1), mixed :mixed 说明一个参数可以接受多种不同的(但并不必须是所有的)类型。

(2), number :number 说明一个参数可以是 integer 或者 float。

(3), callback :有些诸如 call_user_function() 或 usort() 的函数接受用户自定义的函数作为一个参数。Callback 函数不仅可以是一个简单的函数,它还可以是一个对象的方法,包括静态类的方法。 一个 PHP 函数用函数名字符串来传递。可以传递任何内置的或者用户自定义的函数,除了 array(),echo(),empty(),eval(),exit(),isset(),list(),print() 和 unset()。

一个对象的方法以数组的形式来传递,数组的下标 0 指明对象名,下标 1 指明方法名。

对于没有实例化为对象的静态类,要传递其方法,将数组 0 下标指明的对象名换成该类的名称即可。

2, 字符串可以用三种字面上的方法定义。

(1), 单引号: 除可转义(')和字符串末的(\),其中出现的变量和转义序列不会被其对应的值替代。

<?php // 输出结果: Arnold once said: "I'll be back \" echo 'Arnold once said: "I\'ll be back \\"';//转义表示(')和字符串末的(\)用(\)转义 // 两个输出结果一样: You deleted C:\*.*? echo 'You deleted C:\\*.*?';//可转义(\)本身,但不必要 echo 'You deleted C:\*.*?'; //因为试图转义除(')和字符串末的(\)之外字符都会连带转义(\) // 输出结果: This will not expand: \n a newline, Variables do not $expand $either echo 'This will not expand: \n a newline, Variables do not $expand $either'; //单引号变量和转义序列不会生效。 ?>

(2), 双引号 :其中出现的变量和转义序列会被解析生效。

序列

含义

\n

换行(LF 或 ASCII 字符 0x0A(10))

\r

回车(CR 或 ASCII 字符 0x0D(13))

\t

水平制表符(HT 或 ASCII 字符 0x09(9))

\\

反斜线

\$

美元符号

\”

双引号

\[0-7]{1,3}

此正则表达式序列匹配一个用八进制符号表示的字符

\x[0-9A-Fa-f]{1,2}

此正则表达式序列匹配一个用十六进制符号表示的字符

此外,如果试图转义任何其它字符,反斜线本身也会被显示出来!

(3), 定界符(PHP4开始支持): 格式严格干净。结束标识符格式严格,前面必须只有上段换行符(\x41 ,\r),后面只有分号和换行符。不能用定界符语法初始化类成员。必须用其它字符串语法替代。其中出现的变量和转义序列会被解析生效。而且其中可以省略转义引号。

<?php $str = <<<EOD //标识符(必须遵循 PHP 中标签的命名规则) Example of string spanning multiple lines using heredoc syntax. EOD; //结束标识符格式必须干净

3, 类型转换:PHP 在变量定义中不需要(或不支持)明示的类型定义;变量类型是根据使用该变量的上下文所决定的。

A, 类型戏法:

B, 类型强制转换:和 C 中的非常像:在要转换的变量之前加上用括号括起来的目标类型。

<?php $foo = 10; // $foo is an integer $bar = (boolean) $foo; // $bar is a boolean ?> 允许的强制转换有: (int),(integer) - 转换成整型 (bool),(boolean) - 转换成布尔型 (float),(double),(real) - 转换成浮点型 (string) - 转换成字符串 (array) - 转换成数组 (object) - 转换成对象

四,PHP变量和常量

1, 变量:$variable,变量以字母、_开始,不能有空格。赋值$variable=value。PHP的变量是弱类型,可直接赋值而不需要显示声明数据类型,是由 PHP 根据该变量使用的上下文在运行时决定其类型。

PHP 中变量,标签的命名规则:只能包含字母数字下划线,而且必须以下划线或非数字字符开始。

2, 变量解析: 当用双引号或者定界符指定字符串时,其中的变量会被解析。

有两种语法,一种简单的和一种复杂的。

A, 简单语法最通用和方便,它提供了解析变量,数组值,或者对象属性的方法。 如果遇到美元符号($),解析器会尽可能多地取得后面的字符以组成一个合法的变量名。如果想明示指定名字的结束,用花括号把变量名括起来。

B, 复杂语法是 PHP 4 引进的,可以用花括号括起一个表达式。事实上,用此语法可以在字符串中包含任何在名字空间的值。仅仅用和在字符串之外同样的方法写一个表达式,然后用 { 和 } 把它包含进来。因为不能转义“{”,此语法仅在 $ 紧跟在 { 后面时被识别(用“{\$”或者“\{$”来得到一个字面上的“{$”)。注意,如果数组索引用了字符,要用单引号括起来。

3, 定义常量:define(“CONSTANS_NAME”,value)

五,操作符

1)赋值操作符:=

2)算术操作符:+,-,*,/,%(取模)

3)连接操作符:. ,无论操作数是什么,都当成String,结果返回String

4)合计赋值操作符(Combined Assignment Operators):+=,*=,/=,-=,%=,.=

5)自动增减操作符(Automatically Incrementing and Decrementing):

(1)$variable+=1 ⇔$variable++;$variable-=1 ⇔$variable-,跟c语言一样,先做其他操作,后++或-

(2)++$variable,-$variable,先++或-,再做其他操作

6)比较操作符:

= =(左边等于右边),!=(左边不等于右边), = = =(左边等于右边,且数据类型相同), >=,>,<,<=

7)逻辑操作符:|| or,&& and,xor(当左右两边有且只有一个是true,返回true),!

六,流程控制语句

1)if语句:

(1)if(expression)

{ //code to excute if expression evaluates to true }

(2)if(expression)

{ } else { }

(3)if(expression1)

{ } elseif(expression2) { } else { }

2) swich语句

switch ( expression ) { case result1: // execute this if expression results in result1 break; case result2: // execute this if expression results in result2 break; default: // execute this if no break statement // has been encountered hitherto }

3) ?操作符:

( expression )?returned_if_expression_is_true:returned_if_expression_is_false;

4) while语句:

(1) while ( expression ) { // do something } (2)do { // code to be executed } while ( expression );

5) for语句:

for ( initialization expression; test expression; modification expression ) { // code to be executed }

6) break;continue

七,函数

1) 定义函数:

function function_name($argument1,$argument2,……) //形参 { //function code here; }

2) 函数调用

function_name($argument1,$argument2,……); //形参

3) 动态函数调用(Dynamic Function Calls):

1: <html> 2: <head> 3: <title>Listing 6.5</title> 4: </head> 5: <body> 6: <?php 7: function sayHello() { //定义函数sayHello 8: print "hello<br>"; 9: } 10: $function_holder = "sayHello"; //将函数名赋值给变量$function_holder 11: $function_holder(); //变量$function_holder成为函数sayHello的引用, //调用$function_holder()相当于调用sayHello 12: ?> 13: </body> 14: </html>

4) 变量作用域:

全局变量:

1: <html> 2: <head> 3: <title>Listing 6.8</title> 4: </head> 5: <body> 6: <?php 7: $life=42; 8: function meaningOfLife() { 9: global $life; /*在此处重新声明$life为全局变量,在函数内部访问全局变量必须这样, 如果在函数内改变变量的值,将在所有代码片段改变*/ 10: print "The meaning of life is $life<br>"; 11: } 12: meaningOfLife(); 13: ?> 14: </body> 15: </html>

5) 使用static

1: <html> 2: <head> 3: <title>Listing 6.10</title> 4: </head> 5: <body> 6: <?php 7: function numberedHeading( $txt ) { 8: static $num_of_calls = 0; 9: $num_of_calls++; 10: print "<h1>$num_of_calls. $txt</h1>"; 11: } 12: numberedHeading("Widgets"); //第一次调用时,打印$num_of_calls值为1 13: print("We build a fine range of widgets<p>"); 14: numberedHeading("Doodads"); /*第一次调用时,打印$num_of_calls值为2, 因为变量是static型的,static型是常驻内存的*/ 15: print("Finest in the world<p>"); 16: ?> 17: </body> 18: </html>

6) 传值(value)和传址(reference):

传值:function function_name($argument)

1: <html> 2: <head> 3: <title>Listing 6.13</title> 4: </head> 5: <body> 6: <?php 7: function addFive( $num ) { 8: $num += 5; 9: } 10: $orignum = 10; 11: addFive( &$orignum ); 12: print( $orignum ); 13: ?> 14: </body> 15: </html>

结果:10

传址:funciton function_name(&$argument)

1: <html> 2: <head> 3: <title>Listing 6.14</title> 4: </head> 5: <body> 6: <?php 7: function addFive( &$num ) { 8: $num += 5; /*传递过来的是变量$num的引用, 因此改变形参$num的值就是真正改变变量$orignum物理内存中保存的值*/ 9: } 10: $orignum = 10; 11: addFive( $orignum ); 12: print( $orignum ); 13: ?> 14: </body> 15: </html>

结果:15

7) 创建匿名函数:create_function(‘string1’,’string2’); create_function是PHP内建函数,专门用于创建匿名函数,接受两个string型参数,第一个是参数列表,第二个是函数的主体

1: <html> 2: <head> 3: <title>Listing 6.15</title> 4: </head> 5: <body> 6: <?php 7: $my_anon = create_function( '$a, $b', 'return $a+$b;' ); 8: print $my_anon( 3, 9 ); 9: // prints 12 10: ?> 11: </body> 12: </html>

8) 判断函数是否存在:function_exists(function_name),参数为函数名

八,用PHP连接MySQL

1) 连接:&conn=mysql_connect(“localhost”, “joeuser”, “somepass”);

2) 关闭连接:mysql_close($conn);

3) 数据库与连接建立联系:mysql_select_db(database name, connection index);

4) 将SQL语句给MySQL执行:$result = mysql_query($sql, $conn); 增删改查都是这句 5) 检索数据:返回记录数:$number_of_rows = mysql_num_rows($result); 将记录放入数组:$newArray = mysql_fetch_array($result); 例子: <code> 1: <?php 2: open the connection

3: $conn = mysql_connect("localhost", "joeuser", "somepass"); 4: // pick the database to use 5: mysql_select_db("testDB",$conn); 6: // create the SQL statement 7: $sql = "SELECT * FROM testTable"; 8: // execute the SQL statement 9: $result = mysql_query($sql, $conn) or die(mysql_error());

10: go through each row in the result set and display data 11: while ($newArray = mysql_fetch_array($result)) { 12: give a name to the fields 13: $id = $newArray['id']; 14: $testField = $newArray['testField']; 15: echo the results onscreen 16: echo “The ID is $id and the text is $testField <br>”; 17: } 18: ?> </code> ===== 九,PHP连接Access ===== 16、PHP连接Access: <code> <? $dbc=new com(“adodb.connection”); $dbc→open(“driver=microsoft access driver (*.mdb);dbq=c:\member.mdb”); $rs=$dbc→execute(“select * from tablename”); $i=0; while (!$rs→eof){ $i+=1 $fld0=$rs→fields[“UserName”]; $fld0=$rs→fields[“Password”]; …. echo “$fld0→value $fld1→value ….”; $rs→movenext(); } $rs→close(); ?> </code> ===== 十,表单 ===== 1, 接受表单元素:$_POST[表单元素名], 如<input type=text name=user>ó$_POST[user] 2, 接受url中queryString中值(GET方式):$_GET[queryString] ===== 十一,页面转向 ===== 12、转向其他页面:header(“Location: http://www.samspublishing.com”); ===== 十二,字符串操作 ===== 13、字符串操作: 1)explode(“-”,str)óJava中的splite 2)str_replace($str1,$str2,$str3) ⇒$str1要查找的字符串,$str2用来替换的字符串,$str3从这个字符串开始查找替换 3)substr_replace: ===== 十二,session ===== 1)打开session:session_start(); 也可以在php.ini设置session_auto_start=1,不必再每个script都写这句,但是默认为0,则必须要写。

2)给session赋值:$_SESSION[session_variable_name]=$variable;

3)访问session:$variable =$_SESSION[session_variable_name];

4)销毁session:session_destroy();

十三,打印语句

print,与c语言相同

十四,分类

15、显示分类的完整例子:

1: <?php
  2: //connect to database
  3: $conn = mysql_connect("localhost", "joeuser", "somepass")
  4:     or die(mysql_error());
  5: mysql_select_db("testDB",$conn) or die(mysql_error());
  6:
  7: $display_block = "<h1>My Categories</h1>
  8: <P>Select a category to see its items.</p>";
  9:
 10: //show categories first
 11: $get_cats = "select id, cat_title, cat_desc from
 12:     store_categories order by cat_title";
 13: $get_cats_res = mysql_query($get_cats) or die(mysql_error());
 14:
 15: if (mysql_num_rows($get_cats_res) < 1) { //如果返回记录行数小于1,则说明没有分类
 16:    $display_block = "<P><em>Sorry, no categories to browse.</em></p>";
 17: } else {
 18:
 19:    while ($cats = mysql_fetch_array($get_cats_res)) { //将记录放入变量$cats中
 20:        $cat_id = $cats[id];
 21:        $cat_title = strtoupper(stripslashes($cats[cat_title]));
 22:        $cat_desc = stripslashes($cats[cat_desc]);
 23:
 24:         $display_block .= "<p><strong><a
 25:         href=\"$_SERVER[PHP_SELF][U1] ?cat_id=$cat_id\">$cat_title</a></strong>
//点击此url,刷新本页,第 28行读取cat_id,显示相应分类的条目
 26:         <br>$cat_desc</p>";
 27:
 28:        if ($_GET[cat_id] == $cat_id) { //选择一个分类,看下面的条目
 29:            //get items
 30:            $get_items = "select id, item_title, item_price
 31:            from store_items where cat_id = $cat_id
 32:             order by item_title";
 33:            $get_items_res = mysql_query($get_items) or die(mysql_error());
 34:
 35:            if (mysql_num_rows($get_items_res) < 1) {
 36:                 $display_block = "<P><em>Sorry, no items in
 37:                  this category.</em></p>";
 38:             } else {
 39:
 40:                 $display_block .= "<ul>";
 41:
 42:                 while ($items = mysql_fetch_array($get_items_res)) {
 43:                     $item_id = $items[id];
 44:                     $item_title = stripslashes($items[item_title]);

 45:                     $item_price = $items[item_price];
 46:
 47:                     $display_block .= "<li><a
 48:                      href=\"showitem.php?item_id=$item_id\">$item_title</a>
 49:                      </strong> (\$$item_price)";
 50:                 }
 51:
 52:                 $display_block .= "</ul>";
 53:            }
 54:         }
 55:     }
 56: }
 57: ?>
 58: <HTML>
 59: <HEAD>
 60: <TITLE>My Categories</TITLE>
 61: </HEAD>
 62: <BODY>
 63: <? print $display_block; ?>
 64: </BODY>
 65: </HTML>

十五,Hello World程序范例

Hello World程序

下面是一个在标准输出设备上输出Hello World的简单程序,这种程序通常作为开始学习编程语言时的第一个程序:

<?php echo 'Hello World!'; ?>

<? echo 'Hello World!'; ?>

从中我们可以看出,PHP语言是嵌入在“<?php…?>”或“<?…?>” 之间的部分。而这个程序最终结果将是:

Hello World!

但建议您使用 <?php … ?> 此种方式撰写您的程序,在php缺省的设定档php.ini中,通常此设定值为Off,若您有打开此设定的需要,您可以参见 php.ini 中关于 “short_open_tag = Off ”这部份的设定。

phpinfo

下面是一个在标准输出设备上输出关于PHP的设置的简单程序, 如PHP变量, 模块:

<?php phpinfo(); ?>