abc_begin

导航

PHP快速入门

整理一些PHP最基本的语法,旨在快速入门。

 

PHP的print

 1 <?php
 2 
 3      # First Example
 4 
 5      print <<<END
 6 
 7      This uses the "here document" syntax to output
 8 
 9      multiple lines with $variable interpolation. Note
10 
11      that the here document terminator must appear on a
12 
13      line with just a semicolon no extra whitespace!
14 
15      END;
16      # Second Example
17 
18      print "This spans
19 
20      multiple lines. The newlines will be
21 
22      output as well";
23 
24 ?>

对于打印多行的情况,可以使用上面的2种方法;另外PHP中的注释分为单行注释和多行注释,单行注释使用“#”或C语言的注释方法,多行注释使用C语言的注释方法。

 

PHP print和echo语句

echo 和 print 区别:

  • echo - 可以输出一个或多个字符串
  • print - 只允许输出一个字符串,返回值总为 1

提示:echo 输出的速度比 print 快, echo 没有返回值,print有返回值1。

 

PHP的变量

(1)所有变量在 PHP 标有一个美元符号($)。

(2)PHP 变量没有内在类型——一个变量事先不知道是否会用于存储数字或字符串。

(3)变量在第一次赋值给它的时候被创建,PHP 可以自动地从一个类型转换成另一个类型。

(4)PHP 一共有八种数据类型可以供我们用来构造变量:

  • 整型:是整数,没有小数点,像 4195。
  • 浮点型:浮点数,如 3.14159 或 49.1。
  • 布尔值:只有两个可能值或真或假。
  • 空:是一种特殊的类型只有一个值:空。
  • 字符串类型:字符序列,像'PHP 支持字符串操作'
  • 数组:有命名和索引所有值的集合。
  • 对象:是程序员定义类的实例化,可以打包其他类型的值和属于这个类的函数。
     1 <?php
     2 class Car
     3 {
     4     var $color;
     5     function Car($color="green") {
     6       $this->color = $color;
     7     }
     8     function what_color() {
     9       return $this->color;
    10     }
    11 }
    12 
    13 function print_vars($obj) {
    14    foreach (get_object_vars($obj) as $prop => $val) {
    15      echo "\t$prop = $val\n";
    16    }
    17 }
    18 
    19 // instantiate one object
    20 $herbie = new Car("white");
    21 
    22 // show herbie properties
    23 echo "\herbie: Properties\n";
    24 print_vars($herbie);
    25 
    26 ?>  

    运行结果:

    \herbie: Properties
            color = white
      

    get_object_var($object),返回一个数组。获取$object对象中的属性,组成一个数组

  • 资源:特殊变量持有引用外部资源到 PHP(如数据库连接)。

 

PHP的变量赋值多行内容

也可以用上面类似的方法给变量赋值多行的语句内容值。

 1 <?php
 2 
 3 $channel =<<<_XML_
 4     <channel>
 5     <title>What's For Dinner<title>
 6     <link>http://menu.example.com/<link>
 7     <description>Choose what to eat tonight.</description>
 8     </channel>
 9 _XML_;
10 
11 echo <<<END
12     This uses the "here document" syntax to output
13     multiple lines with variable interpolation. Note
14     that the here document terminator must appear on a
15     line with just a semicolon. no extra whitespace!
16     <br />
17 END;
18 
19 print $channel;
20 ?>

运行结果:

    This uses the "here document" syntax to output
    multiple lines with variable interpolation. Note
    that the here document terminator must appear on a
    line with just a semicolon. no extra whitespace!

    <channel>
    <title>What's For Dinner<title>
    <link>http://menu.example.com/<link>
    <description>Choose what to eat tonight.</description>

注意tab也是生效了的。

 

全局变量和静态变量

(1)全局变量:通过将关键字 GLOBAL 放在变量前该变量可以被确认为全局变量。

$a 变量在函数外定义,无法在函数内使用,如果要在一个函数中访问一个全局变量,需要使用 global 关键字。该关键字用于函数内访问全局变量。

在函数内调用函数外定义的全局变量,我们需要在函数中的变量前加上 global 关键字

 1 <?php
 2 
 3 $a = 22;
 4 
 5 function change()
 6 {
 7         GLOBAL $a;
 8         $a += 2;
 9 }
10 
11 change();
12 
13 print $a;
14 ?>

运行结果:

24

PHP 将所有全局变量存储在一个名为 $GLOBALS[index] 的数组中。 index 保存变量的名称。这个数组可以在函数内部访问,也可以直接用来更新全局变量。

上面的代码也可以写为下面这种形式:

 1 <?php
 2 
 3 $a = 22;
 4 
 5 function change()
 6 {
 7         $GLOBALS['a'] += 2;
 8 }
 9 
10 change();
11 
12 print $a;
13 ?>

(2)静态变量:当一个函数完成时,它的所有变量通常都会被删除。然而,有时候希望某个局部变量不要被删除。要做到这一点,在第一次声明变量时使用 static 关键字

 1 <?php
 2 
 3 function change()
 4 {
 5         STATIC $a = 0;
 6         $a += 2;
 7         print $a;
 8         print "\n";
 9 }
10 
11 change();
12 change();
13 change();
14 
15 ?>

运行结果:

2
4
6

 

常量

常量和变量之间的区别:

  • 常量前面没有必要写美元符号($),在变量前必须编写一个美元符号。
  • 常量只能用 define() 函数定义,而不能通过简单的赋值语句。
  • 常量可以不用理会变量范围的规则而在任何地方定义和访问。
  • 常量一旦定义就不能被重新定义或者取消定义。
  • 可以使用函数 constant()读取一个常数的值。
 1 <?php
 2 
 3 define("MINSIZE", 50);
 4 
 5 echo MINSIZE;
 6 echo "\n";
 7 
 8 echo constant("MINSIZE"); // same thing as the previous line
 9 echo "\n";
10 
11 $value = constant("MINSIZE"); 
12 print $value;
13 echo "\n";
14 ?>

运行结果:

50
50
50

 

PHP7+ 版本新增整除运算符 intdiv()

1 <?php
2 
3 var_dump(intdiv(10, 3));
4 
5 echo intdiv(10, 3);
6 
7 ?>

运行结果:

int(3)
3

 

PHP比较运算符

除了下表列出的,其余的和C语言类似,不再赘述

运算符名称描述实例
x == y 等于 如果 x 等于 y,则返回 true 5==8 返回 false
x === y 绝对等于 如果 x 等于 y,且它们类型相同,则返回 true 5==="5" 返回 false
x != y 不等于 如果 x 不等于 y,则返回 true 5!=8 返回 true
x <> y 不等于 如果 x 不等于 y,则返回 true 5<>8 返回 true
x !== y 绝对不等于 如果 x 不等于 y,或它们类型不相同,则返回 true 5!=="5" 返回 true

 

结构控制

有2种方式:if和switch,和C语言类似。

 1 <?php
 2 
 3 $d = date("D");
 4 if ($d == "Fri")
 5         echo "Have a nice weekend!\n"; 
 6 elseif ($d == "Sun")
 7         echo "Fuck!\n"; 
 8 else
 9         echo "Have a nice day!\n"; 
10 
11 ?>

运行结果:

Fuck!

 

循环类型

有4种方式:for、while、do...while、foreach,前面3种和C语言中类似,不再赘述了。

foreach 语句用于循环遍历数组。每进行一次循环,当前数组元素的值就会被赋值给 value 变量,数组指针会逐一地移动以此类推。

1 <?php
2 
3 $array = array( 1, 2, 3, 4, 5);
4 foreach( $array as $value )
5 {
6         echo "Value is $value \n";
7 }
8 
9 ?>

运行结果:

Value is 1 
Value is 2 
Value is 3 
Value is 4 
Value is 5

 

数组

有三种不同类型的数组,每一个数组的值可以通过一个被称为数组索引 ID 键来访问。

(1)数字数组:也成为索引数组,数组以一个数字作为索引。值在线性中存储和访问。这些数组可以存储数字、字符串和任何对象但是他们将数字作为索引。默认情况下,数组索引从 0 开始。

 1 <?php
 2 
 3 /* First method to create array. */
 4 $numbers = array( 1, 2, 3, 4, 5);
 5 foreach( $numbers as $value )
 6 {
 7         echo "Value is $value \n";
 8 }
 9 echo "------------------------- \n";
10 
11 /* Second method to create array. */
12 $numbers[0] = "one";
13 $numbers[1] = "two";
14 $numbers[2] = "three";
15 foreach( $numbers as $value )
16 {
17         echo "Value is $value \n";
18 }
19 echo "------------------------- \n";
20 
21 /* Third method to create array. */
22 $aa[0] = "aa0";
23 $aa[1] = "aa1";
24 $aa[2] = "aa2";
25 foreach( $aa as $value )
26 {
27         echo "Value is $value \n";
28 }
29 
30 ?>

运行结果:

Value is 1 
Value is 2 
Value is 3 
Value is 4 
Value is 5 
------------------------- 
Value is one 
Value is two 
Value is three 
Value is 4 
Value is 5 
------------------------- 
Value is aa0 
Value is aa1 
Value is aa2

通过count()可以获取数组长度,并且用这个可以更方便的遍历数组

 1 <?php
 2 $cars = array("Volvo", "BMW", "Toyota");
 3 $arrlength = count($cars);
 4  
 5 for($x = 0; $x < $arrlength; $x++)
 6 {
 7     echo $cars[$x];
 8     echo "<br>";
 9 }
10 ?>

运行结果:

Volvo
BMW
Toyota

(2)关联数组:数组以字符串作为索引。这个数组存储元素值与键值不是一个严格的线性索引顺序。数值数组和关联数组功能非常的相似,他们只是有不同的索引。关联数组将字符串作为索引,这样就可以建立一个强大的键和值的结构体系。注意: 不要使关联数组在双引号内,否则打印它不会返回任何值。

可以将员工的工资存储在一个数组,用数字索引定义数组并不是最好的选择。相反,我们可以使用员工的名字作为关联数组的键,将工资作为键的值。

 1 <?php
 2 function print_fun($salaries)
 3 {
 4         echo "Salary of mohammad is ". $salaries['mohammad'] . "\n";
 5         echo "Salary of qadir is ".  $salaries['qadir']. "\n";
 6         echo "Salary of zara is ".  $salaries['zara']. "\n";
 7 }
 8 
 9 function print_foreach($salaries)
10 {
11         var_dump($salaries);
12         foreach ($salaries as $value)
13         {
14                 var_dump($value);
15                 echo $value. "\n";
16         }
17 }
18 
19 /* First method to associate create array. */
20 $salaries = array( 
21                 "mohammad" => 2000, 
22                 "qadir" => 1000, 
23                 "zara" => 500
24                 );
25 print_fun($salaries);
26 
27 /* Second method to create array. */
28 $salaries['mohammad'] = "high";
29 $salaries['qadir'] = "medium";
30 $salaries['zara'] = "low";
31 print_fun($salaries);
32 
33 /* third method to create array. */
34 $salaries['mohammad'] = 1;
35 $salaries['qadir'] = 2;
36 $salaries['zara'] = 3;
37 print_foreach($salaries);
38 ?>

运行结果:

Salary of mohammad is 2000
Salary of qadir is 1000
Salary of zara is 500
Salary of mohammad is high
Salary of qadir is medium
Salary of zara is low
array(3) {
  ["mohammad"]=>
  int(1)
  ["qadir"]=>
  int(2)
  ["zara"]=>
  int(3)
}
int(1)
1
int(2)
2
int(3)
3

上面这种遍历方法很挫,可以用下面的方法来搞

 1 <?php
 2 function print_fun($salaries)
 3 {
 4         echo "Salary of mohammad is ". $salaries['mohammad'] . "\n";
 5         echo "Salary of qadir is ".  $salaries['qadir']. "\n";
 6         echo "Salary of zara is ".  $salaries['zara']. "\n";
 7 }
 8 
 9 function print_foreach($salaries)
10 {
11         var_dump($salaries);
12         foreach ($salaries as $key => $value)
13         {
14                 var_dump($key);
15                 var_dump($value);
16                 echo "Key=" . $key . ", Value=" . $value. "\n";
17         }
18 }
19 
20 /* First method to associate create array. */
21 $salaries = array( 
22                 "mohammad" => 2000, 
23                 "qadir" => 1000, 
24                 "zara" => 500
25                 );
26 print_fun($salaries);
27 
28 /* Second method to create array. */
29 $salaries['mohammad'] = "high";
30 $salaries['qadir'] = "medium";
31 $salaries['zara'] = "low";
32 print_fun($salaries);
33 
34 /* third method to create array. */
35 $salaries['mohammad'] = 1;
36 $salaries['qadir'] = 2;
37 $salaries['zara'] = 3;
38 print_foreach($salaries);
39 ?>

运行结果:

Salary of mohammad is 2000
Salary of qadir is 1000
Salary of zara is 500
Salary of mohammad is high
Salary of qadir is medium
Salary of zara is low
array(3) {
 ["mohammad"]=>
 int(1)
 ["qadir"]=>
 int(2)
 ["zara"]=>
 int(3)
}
string(8) "mohammad"
int(1)
Key=mohammad, Value=1
string(5) "qadir"
int(2)
Key=qadir, Value=2
string(4) "zara"
int(3)
Key=zara, Value=3

(3)多维数组:包含一个或多个数组,数组值可以使用多个索引访问。在多维数组中,主数组中的每个元素也是一个数组。在子数组中的每个元素也可以是数组等等,多维数组中的值是使用多个索引访问。

 1 <?php
 2 
 3 function print_foreach($marks)
 4 {
 5         var_dump($marks);
 6         echo "================================\n";
 7         foreach ($marks as $value)
 8         {
 9                 var_dump($value);
10                 echo "------------------------------\n";
11                 foreach ($value as $value_inner)
12                 {
13                         echo $value_inner. "\n";
14                 }
15                 echo "\n\n";
16         }
17 }
18 
19 $marks = array( 
20                 "mohammad" => array
21                 (
22                  "physics" => 35,
23                  "maths" => 30,
24                  "chemistry" => 3
25                 ),
26                 "qadir" => array
27                 (
28                  "physics" => 30,
29                  "maths" => 32,
30                  "chemistry" => 29
31                 ),
32                 "zara" => array
33                 (
34                  "physics" => 31,
35                  "maths" => 22,
36                  "chemistry" => 39
37                 )
38               );
39 /* Accessing multi-dimensional array values */
40 echo "Marks for mohammad in physics : " ;
41 echo $marks['mohammad']['physics'] . "\n"; 
42 echo "Marks for qadir in maths : ";
43 echo $marks['qadir']['maths'] . "\n"; 
44 echo "Marks for zara in chemistry : " ;
45 echo $marks['zara']['chemistry'] . "\n"; 
46 
47 print_foreach($marks);
48 
49 ?>

运行结果:

Marks for mohammad in physics : 35
Marks for qadir in maths : 32
Marks for zara in chemistry : 39
array(3) {
  ["mohammad"]=>
  array(3) {
    ["physics"]=>
    int(35)
    ["maths"]=>
    int(30)
    ["chemistry"]=>
    int(3)
  }
  ["qadir"]=>
  array(3) {
    ["physics"]=>
    int(30)
    ["maths"]=>
    int(32)
    ["chemistry"]=>
    int(29)
  }
  ["zara"]=>
  array(3) {
    ["physics"]=>
    int(31)
    ["maths"]=>
    int(22)
    ["chemistry"]=>
    int(39)
  }
}
================================
array(3) {
  ["physics"]=>
  int(35)
  ["maths"]=>
  int(30)
  ["chemistry"]=>
  int(3)
}
------------------------------
35
30
3


array(3) {
  ["physics"]=>
  int(30)
  ["maths"]=>
  int(32)
  ["chemistry"]=>
  int(29)
}
------------------------------
30
32
29


array(3) {
  ["physics"]=>
  int(31)
  ["maths"]=>
  int(22)
  ["chemistry"]=>
  int(39)
}
------------------------------
31
22
39

重新使用遍历方法:

 1 <?php
 2 
 3 function print_foreach($marks)
 4 {
 5         var_dump($marks);
 6         echo "================================\n";
 7         foreach ($marks as $value_outer)
 8         {
 9                 var_dump($value_outer);
10                 echo "------------------------------\n";
11                 foreach ($value_outer as $key => $value_inner)
12                 {
13                         echo "key = " . $key . ", value = " . $value_inner. "\n";
14                 }
15                 echo "\n\n";
16         }
17 }
18 
19 $marks = array( 
20                 "mohammad" => array
21                 (
22                  "physics" => 35,
23                  "maths" => 30,
24                  "chemistry" => 3
25                 ),
26                 "qadir" => array
27                 (
28                  "physics" => 30,
29                  "maths" => 32,
30                  "chemistry" => 29
31                 ),
32                 "zara" => array
33                 (
34                  "physics" => 31,
35                  "maths" => 22,
36                  "chemistry" => 39
37                 )
38               );
39 /* Accessing multi-dimensional array values */
40 echo "Marks for mohammad in physics : " ;
41 echo $marks['mohammad']['physics'] . "\n"; 
42 echo "Marks for qadir in maths : ";
43 echo $marks['qadir']['maths'] . "\n"; 
44 echo "Marks for zara in chemistry : " ;
45 echo $marks['zara']['chemistry'] . "\n"; 
46 
47 print_foreach($marks);
48 
49 ?>

运行结果:

Marks for mohammad in physics : 35
Marks for qadir in maths : 32
Marks for zara in chemistry : 39
array(3) {
 ["mohammad"]=>
 array(3) {
   ["physics"]=>
   int(35)
   ["maths"]=>
   int(30)
   ["chemistry"]=>
   int(3)
 }
 ["qadir"]=>
 array(3) {
   ["physics"]=>
   int(30)
   ["maths"]=>
   int(32)
   ["chemistry"]=>
   int(29)
 }
 ["zara"]=>
 array(3) {
   ["physics"]=>
   int(31)
   ["maths"]=>
   int(22)
   ["chemistry"]=>
   int(39)
 }
}
================================
array(3) {
 ["physics"]=>
 int(35)
 ["maths"]=>
 int(30)
 ["chemistry"]=>
 int(3)
}
------------------------------
key = physics, value = 35
key = maths, value = 30
key = chemistry, value = 3
array(3) {
 ["physics"]=>
 int(30)
 ["maths"]=>
 int(32)
 ["chemistry"]=>
 int(29)
}
------------------------------
key = physics, value = 30
key = maths, value = 32
key = chemistry, value = 29
array(3) {
 ["physics"]=>
 int(31)
 ["maths"]=>
 int(22)
 ["chemistry"]=>
 int(39)
}
------------------------------
key = physics, value = 31
key = maths, value = 22
key = chemistry, value = 39

 

PHP数组排序函数

  • sort() - 对数组进行升序排列
  • rsort() - 对数组进行降序排列
  • asort() - 根据关联数组的值,对数组进行升序排列
  • ksort() - 根据关联数组的键,对数组进行升序排列
  • arsort() - 根据关联数组的值,对数组进行降序排列
  • krsort() - 根据关联数组的键,对数组进行降序排列

 

字符串

单引号串和双引号串在 PHP 中的处理是不相同的。双引号串中的内容可以被解释而且替换,而单引号串中的内容总被认为是普通字符。

(1)字符串并置运算符:要把两个变量连接在一起,请使用这个点运算符 (.)

(2)使用 strlen() 函数:strlen() 函数用于计算字符串的长度。

(3)使用 strpos() 函数:strpos() 函数用于在字符串内检索一段字符串或一个字符。如果在字符串中找到匹配,该函数会返回第一个匹配的位置。如果未找到匹配,则返回 FALSE。

 1 <?php
 2 
 3 $txt1="Hello World";
 4 $txt2="1234";
 5 echo $txt1 . " " . $txt2 . "\n";
 6 
 7 echo strlen($txt2) . "\n";
 8 
 9 echo strpos($txt1, "Wo") . "\n";
10 
11 ?>

运行结果:

Hello World 1234
4
6

 

函数

下面的例子里面包括了引用参数、返回值、默认参数等用法。

 1 <?php
 2 function add($num)
 3 {
 4         $num += 5;
 5         return $num;
 6 }
 7 
 8 #可以通过在变量名称前加&符号传递一个参数引用变量,在函数调用时或函数定义时
 9 function add_and_modify(&$num)
10 {
11         $num += 6;
12         return $num;
13 }
14 
15 function default_num($num = 10)
16 {
17         echo $num . "\n";
18 }
19 
20 $orignum = 10;
21 $r1 = add($orignum);
22 echo $orignum . "\t". $r1 . "\n";
23 $r2 = add_and_modify($orignum);
24 echo $orignum . "\t". $r2 . "\n";
25 
26 default_num();
27 default_num(20);
28 
29 ?>

运行结果:

10      15
16      16
10
20

 

构造函数和析构函数

构造函数 ,是一种特殊的方法。主要用来在创建对象时初始化对象, 即为对象成员变量赋初始值,总与new运算符一起使用在创建对象的语句中。

PHP 5 允行开发者在一个类中定义一个方法作为构造函数,语法格式如下:

void __construct ([ mixed $args [, $... ]] )

析构函数(destructor) 与构造函数相反,当对象结束其生命周期时(例如对象所在的函数已调用完毕),系统自动执行析构函数。

PHP 5 引入了析构函数的概念,这类似于其它面向对象的语言,其语法格式如下:

void __destruct ( void )

例子如下:

 1 <?php
 2 class MyDestructableClass {
 3    function __construct() {
 4        print "构造函数\n";
 5        $this->name = "MyDestructableClass";
 6    }
 7 
 8    function __destruct() {
 9        print "销毁 " . $this->name . "\n";
10    }
11 }
12 
13 $obj = new MyDestructableClass();
14 ?>

运行结果:

构造函数
销毁 MyDestructableClass

 

PHP继承及访问控制

PHP 使用关键字 extends 来继承一个类,PHP 不支持多继承,格式如下:

class Child extends Parent {
   // 代码部分
}

访问控制:

PHP 对属性或方法的访问控制,是通过在前面添加关键字 public(公有),protected(受保护)或 private(私有)来实现的。

  • public(公有):公有的类成员可以在任何地方被访问。
  • protected(受保护):受保护的类成员则可以被其自身以及其子类和父类访问。
  • private(私有):私有的类成员则只能被其定义所在的类访问。

类属性必须定义为公有,受保护,私有之一。如果用 var 定义,则被视为公有。

类中的方法可以被定义为公有,私有或受保护。如果没有设置这些关键字,则该方法默认为公有。

 1 <?php
 2 /**
 3  * Define MyClass
 4  */
 5 class MyClass
 6 {
 7     public $public = 'Public';
 8     protected $protected = 'Protected';
 9     private $private = 'Private';
10 
11     function printHello()
12     {
13         echo $this->public. "\n";
14         echo $this->protected. "\n";
15         echo $this->private. "\n";
16     }
17 }
18 
19 $obj = new MyClass();
20 //echo $obj->public; // 这行能被正常执行
21 //echo $obj->protected; // 这行会产生一个致命错误
22 //echo $obj->private; // 这行也会产生一个致命错误
23 $obj->printHello(); // 输出 Public、Protected 和 Private
24 
25 
26 /**
27  * Define MyClass2
28  */
29 class MyClass2 extends MyClass
30 {
31     // 可以对 public 和 protected 进行重定义,但 private 而不能
32     protected $protected = 'Protected2';
33 
34     function printHello()
35     {
36         echo $this->public . "\n";
37         echo $this->protected. "\n";
38         echo $this->private. "\n";
39     }
40 }
41 
42 $obj2 = new MyClass2();
43 //echo $obj2->public; // 这行能被正常执行
44 //echo $obj2->private; // 未定义 private
45 //echo $obj2->protected; // 这行会产生一个致命错误
46 $obj2->printHello(); // 输出 Public、Protected2 和 Undefined
47 
48 ?>

运行结果:

Public
Protected
Private
Public
Protected2
PHP Notice:  Undefined property: MyClass2::$private in /code/main.php on line 38

 

调用父类构造方法

PHP 不会在子类的构造方法中自动的调用父类的构造方法。要执行父类的构造方法,需要在子类的构造方法中调用 parent::__construct() 。

 1 <?php
 2 class BaseClass {
 3    function __construct() {
 4        print "BaseClass 类中构造方法" . PHP_EOL;
 5    }
 6 }
 7 class SubClass extends BaseClass {
 8    function __construct() {
 9        parent::__construct();  // 子类构造方法不能自动调用父类的构造方法
10        print "SubClass 类中构造方法" . PHP_EOL;
11    }
12 }
13 class OtherSubClass extends BaseClass {
14     // 继承 BaseClass 的构造方法
15 }
16 
17 // 调用 BaseClass 构造方法
18 $obj = new BaseClass();
19 
20 // 调用 BaseClass、SubClass 构造方法
21 $obj = new SubClass();
22 
23 // 调用 BaseClass 构造方法
24 $obj = new OtherSubClass();
25 ?>

运行结果:

BaseClass 类中构造方法
BaseClass 类中构造方法
SubClass 类中构造方法
BaseClass 类中构造方法

 

接口

使用接口(interface),可以指定某个类必须实现哪些方法,但不需要定义这些方法的具体内容。

接口是通过 interface 关键字来定义的,就像定义一个标准的类一样,但其中定义所有的方法都是空的。

接口中定义的所有方法都必须是公有,这是接口的特性。

要实现一个接口,使用 implements 操作符。类中必须实现接口中定义的所有方法,否则会报一个致命错误。类可以实现多个接口,用逗号来分隔多个接口的名称。

 1 <?php
 2 
 3 // 声明一个'iTemplate'接口
 4 interface iTemplate
 5 {
 6     public function setVariable($name, $var);
 7     public function getHtml($template);
 8 }
 9 
10 
11 // 实现接口
12 class Template implements iTemplate
13 {
14     private $vars = array();
15   
16     public function setVariable($name, $var)
17     {
18         $this->vars[$name] = $var;
19     }
20   
21     public function getHtml($template)
22     {
23         foreach($this->vars as $name => $value) {
24             $template = str_replace('{' . $name . '}', $value, $template);
25         }
26  
27         return $template;
28     }
29 }

 

抽象类

任何一个类,如果它里面至少有一个方法是被声明为抽象的,那么这个类就必须被声明为抽象的。

定义为抽象的类不能被实例化。

被定义为抽象的方法只是声明了其调用方式(参数),不能定义其具体的功能实现。

继承一个抽象类的时候,子类必须定义父类中的所有抽象方法;另外,这些方法的访问控制必须和父类中一样(或者更为宽松)。例如某个抽象方法被声明为受保护的,那么子类中实现的方法就应该声明为受保护的或者公有的,而不能定义为私有的。此外方法的调用方式必须匹配,即类型和所需参数数量必须一致。例如,子类定义了一个可选参数,而父类抽象方法的声明里没有,则两者的声明并无冲突。

 1 <?php
 2 abstract class AbstractClass
 3 {
 4     // 强制要求子类定义这些方法
 5     abstract protected function getValue();
 6     abstract protected function prefixValue($prefix);
 7 
 8     // 普通方法(非抽象方法)
 9     public function printOut() {
10         print $this->getValue() . PHP_EOL;
11     }
12 }
13 
14 class ConcreteClass1 extends AbstractClass
15 {
16     protected function getValue() {
17         return "ConcreteClass1";
18     }
19 
20     public function prefixValue($prefix) {
21         return "{$prefix}ConcreteClass1";
22     }
23 }
24 
25 class ConcreteClass2 extends AbstractClass
26 {
27     public function getValue() {
28         return "ConcreteClass2";
29     }
30 
31     public function prefixValue($prefix) {
32         return "{$prefix}ConcreteClass2";
33     }
34 }
35 
36 $class1 = new ConcreteClass1;
37 $class1->printOut();
38 echo $class1->prefixValue('FOO_') . PHP_EOL;
39 
40 $class2 = new ConcreteClass2;
41 $class2->printOut();
42 echo $class2->prefixValue('FOO_') . PHP_EOL;
43 ?>

运行结果:

ConcreteClass1
FOO_ConcreteClass1
ConcreteClass2
FOO_ConcreteClass2

 

static关键字

声明类属性或方法为 static(静态),就可以不实例化类而直接访问。

静态属性不能通过一个类已实例化的对象来访问(但静态方法可以)。

由于静态方法不需要通过对象即可调用,所以伪变量 $this 在静态方法中不可用。

静态属性不可以由对象通过 -> 操作符来访问。

自 PHP 5.3.0 起,可以用一个变量来动态调用类。但该变量的值不能为关键字 self,parent 或 static。

 1 <?php
 2 class Foo {
 3   public static $my_static = 'foo';
 4   
 5   public function staticValue() {
 6      return self::$my_static;
 7   }
 8 }
 9 
10 print Foo::$my_static . PHP_EOL;
11 $foo = new Foo();
12 
13 print $foo->staticValue() . PHP_EOL;
14 ?>    

运行结果:

foo
foo

 

Final 关键字
PHP 5 新增了一个 final 关键字。如果父类中的方法被声明为 final,则子类无法覆盖该方法。如果一个类被声明为 final,则不能被继承。
以下代码执行会报错:

 1 <?php
 2 class BaseClass {
 3    public function test() {
 4        echo "BaseClass::test() called" . PHP_EOL;
 5    }
 6    
 7    final public function moreTesting() {
 8        echo "BaseClass::moreTesting() called"  . PHP_EOL;
 9    }
10 }
11 
12 class ChildClass extends BaseClass {
13    public function moreTesting() {
14        echo "ChildClass::moreTesting() called"  . PHP_EOL;
15    }
16 }
17 // 报错信息 Fatal error: Cannot override final method BaseClass::moreTesting()
18 ?>

 

 

本文参考自:

http://wiki.jikexueyuan.com/project/php/

http://www.runoob.com/php/php-tutorial.html

另外,推荐一个在线运行PHP代码的网站:

https://tool.lu/coderunner/ 

posted on 2017-11-26 12:44  LastBattle  阅读(4611)  评论(0编辑  收藏  举报