整理一些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/