function __autoload($classname) { require_once("{$classname}.php") }
spl_autoload_register(function($classname) { require_once("{$classname}.php") });
// 鏈接到服務器,選擇數據庫 $conn = mysql_connect("localhost", "user", "password"); mysql_select_db("database"); // 執行 SQL 查詢 $type = $_POST['type']; $sql = "SELECT * FROM `table` WHERE `type` = {$type}"; $result = mysql_query($sql); // 打印結果 while($row = mysql_fetch_array($result, MYSQL_ASSOC)) { foreach($row as $k => $v) print "{$k}: {$v}\n"; } // 釋放結果集,關閉鏈接 mysql_free_result($result); mysql_close($conn);
爲了可以讓代碼實現數據庫無關,即一段代碼同時適用於多種數據庫(例如以上代碼僅僅適用於MySQL),PHP 官方設計了 PDO.
// 鏈接到數據庫 $conn = new PDO("mysql:host=localhost;dbname=database", "user", "password"); // 預編譯SQL, 綁定參數 $query = $conn->prepare("SELECT * FROM `table` WHERE `type` = :type"); $query->bindParam("type", $_POST['type']); // 執行查詢並打印結果 foreach($query->execute() as $row) { foreach($row as $k => $v) print "{$k}: {$v}\n"; }
// 限制第一個參數爲 MyClass, 第二個參數爲可執行類型,第三個參數爲數組 function MyFunction(MyClass $a, callable $b, array $c) { // ... }
$array = array("key" => "value", "array" => array(1, 2, 3, 4)); $json = json_encode($array); echo "{$json}\n"; $object = json_decode($json); print_r($object);
{"key":"value","array":[1,2,3,4]} stdClass Object ( [key] => value [array] => Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 ) )
if(isAuth()) $authorized = true; if($authorized) include("page.php");
$func = function($arg) { print $arg; }; $func("Hello World");
function arrayPlus($array, $num) { array_walk($array, function(&$v) use($num){ $v += $num; }); }
class A { public function __invoke($str) { print "A::__invoke(): {$str}"; } } $a = new A; $a("Hello World");
A::__invoke(): Hello World
<?php // 命名空間的分隔符是反斜槓,該聲明語句必須在文件第一行。 // 命名空間中能夠包含任意代碼,但只有 **類, 函數, 常量** 受命名空間影響。 namespace XXOO\Test; // 該類的完整限定名是 \XXOO\Test\A , 其中第一個反斜槓表示全局命名空間。 class A{} // 你還能夠在已經文件中定義第二個命名空間,接下來的代碼將都位於 \Other\Test2 . namespace Other\Test2; // 實例化來自其餘命名空間的對象: $a = new \XXOO\Test\A; class B{} // 你還能夠用花括號定義第三個命名空間 namespace Other { // 實例化來自子命名空間的對象: $b = new Test2\B; // 導入來自其餘命名空間的名稱,並重命名, // 注意只能導入類,不能用於函數和常量。 use \XXOO\Test\A as ClassA }
spl_autoload_register( function ($class) { spl_autoload(str_replace("\\", "/", $class)); } );
class A { public function callFuncXXOO() { print $this->funcXXOO(); } public function funcXXOO() { return "A::funcXXOO()"; } } class B extends A { public function funcXXOO() { return "B::funcXXOO"; } } $b = new B; $b->callFuncXXOO();
輸出是:
B::funcXXOO
class A { static public function callFuncXXOO() { print self::funcXXOO(); } static public function funcXXOO() { return "A::funcXXOO()"; } } class B extends A { static public function funcXXOO() { return "B::funcXXOO"; } } $b = new B; $b->callFuncXXOO();
狀況就沒這麼樂觀了,輸出是:
A::funcXXOO()
class A { static public function callFuncXXOO() { print static::funcXXOO(); } // ... } // ...
B::funcXXOO
$name = "MyName"; echo <<< TEXT My name is "{$name}". TEXT;
var_dump(<<<EOD Hello World EOD ); class A { const xx = <<< EOD Hello World EOD; public $oo = <<< EOD Hello World EOD; }
Nowdoc 的行爲像一個單引號字符串,不能在其中嵌入變量,和 Heredoc 惟一的區別就是,三個左尖括號後的標識符要以單引號括起來:
$name = "MyName"; echo <<< 'TEXT' My name is "{$name}". TEXT;
My name is "{$name}".
define("XOOO", "Value");
const XXOO = "Value";
// 正確 const XXOO = 1234; // 錯誤 const XXOO = 2 * 617;
echo $a ? $a : "No Value";
echo $a ?: "No Value";
require("xxoo.phar"); require("phar://xxoo.phar/xo/ox.php");
<?php // Code... ?>
<? /* Code... */ ?>
<?php echo $xxoo;?>
<?= $xxoo;?>
// 原來的數組寫法 $arr = array("key" => "value", "key2" => "value2"); // 簡寫形式 $arr = ["key" => "value", "key2" => "value2"];
// Traits不能被單獨實例化,只能被類所包含 trait SayWorld { public function sayHello() { echo 'World!'; } } class MyHelloWorld { // 將SayWorld中的成員包含進來 use SayWorld; } $xxoo = new MyHelloWorld(); // sayHello() 函數是來自 SayWorld 構件的 $xxoo->sayHello();
Traits還有不少神奇的功能,好比包含多個Traits, 解決衝突,修改訪問權限,爲函數設置別名等等。
php -S localhost:8000
php -S localhost:8000 index.php
$func = "funcXXOO"; A::{$func}();
(new MyClass)->xxoo();
print func()[0];
function number10() { for($i = 1; $i <= 10; $i += 1) yield $i; }
$array = [ [1, 2, 3], [4, 5, 6], ]; foreach ($array as list($a, $b, $c)) echo "{$a} {$b} {$c}\n";
1 2 3 4 5 6
const A = 2; const B = A + 1; class C { const STR = "hello"; const STR2 = self::STR + ", world"; }
function func($arg = C::STR2)
function add(...$args) { $result = 0; foreach($args as $arg) $result += $arg; return $result; }
$arr = [2, 3]; add(1, ...$arr); // 結果爲 6
namespace Name\Space { const FOO = 42; function f() { echo __FUNCTION__."\n"; } } namespace { use const Name\Space\FOO; use function Name\Space\f; echo FOO."\n"; f(); }