當前位置:才華齋>設計>網頁設計>

PHP必備功能開發

網頁設計 閱讀(1.99W)

PHP有哪些必備開發功能呢?為了幫助大家瞭解更多PHP功能,yjbys小編為大家分析很實用的PHP必備開發功能如下:

PHP必備功能開發

  1、傳遞任意數量的函式引數

我們在或者JAVA程式設計中,一般函式引數個數都是固定的,但是PHP允許你使用任意個數的引數。下面這個示例向你展示了PHP函式的預設引數:

// 兩個預設引數的函式

function foo($arg1 = ”, $arg2 = ”) {

echo “arg1: $arg1n”;

echo “arg2: $arg2n”;

}

foo(‘hello’,'world’);

/* 輸出:

arg1: hello

arg2: world

*/

foo();

/* 輸出:

arg1:

arg2:

*/

//下面這個示例是PHP的不定引數用法,其使用到了 func_get_args()方法:

// 是的,形參列表為空

function foo() {

// 取得所有的傳入引數的陣列

$args = func_get_args();

foreach ($args as $k => $v) {

echo “arg”.($k+1).”: $vn”;

}

}

foo();

/* 什麼也不會輸出 */

foo(‘hello’);

/* 輸出

arg1: hello

*/

foo(‘hello’, ‘world’, ‘again’);

/* 輸出

arg1: hello

arg2: world

arg3: again

  2、使用glob()查詢檔案

大部分PHP函式的函式名從字面上都可以理解其用途,但是當你看到 glob() 的時候,你也許並不知道這是用來做什麼的,其實glob()和scandir() 一樣,可以用來查詢檔案,請看下面的用法:

// 取得所有的字尾為PHP的檔案

$files = glob(‘*’);

print_r($files);

/* 輸出:

Array

(

[0] =>

[1] =>

[2] => post_

[3] =>

)

*/

你還可以查詢多種字尾名:

// 取PHP檔案和TXT檔案

$files = glob(‘*.{php,txt}’, GLOB_BRACE);

print_r($files);

/* 輸出:

Array

(

[0] =>

[1] =>

[2] => post_

[3] =>

[4] =>

[5] =>

)

*/

你還可以加上路徑:

$files = glob(‘../images/a*.jpg’);

print_r($files);

/* 輸出:

Array

(

[0] => ../images/apple.jpg

[1] => ../images/art.jpg

)

*/

如果你想得到絕對路徑,你可以呼叫 realpath() 函式:

$files = glob(‘../images/a*.jpg’);

// applies the function to each array element

$files = array_map(‘realpath’,$files);

print_r($files);

/* output looks like:

Array

(

[0] => C:wampwwwimagesapple.jpg

[1] => C:wampwwwimagesart.jpg

)

*/

  3、獲取記憶體使用情況資訊

PHP的記憶體回收機制已經非常強大,你也可以使用PHP指令碼獲取當前記憶體的使用情況,呼叫memory_get_usage() 函式獲取當期記憶體使用情況,呼叫memory_get_peak_usage() 函式獲取記憶體使用的峰值。參考程式碼如下:

echo “Initial: “ry_get_usage().” bytes n”;

/* 輸出

Initial: 361400 bytes

*/

// 使用記憶體

for ($i = 0; $i < 100000; $i++) {

$array []= md5($i);

}

// 刪除一半的記憶體

for ($i = 0; $i < 100000; $i++) {

unset($array[$i]);

}

echo “Final: “ry_get_usage().” bytes n”;

/* prints

Final: 885912 bytes

*/

echo “Peak: “ry_get_peak_usage().” bytes n”;

/* 輸出峰值

Peak: 13687072 bytes

*/

  4、獲取CPU使用情況資訊

獲取了記憶體使用情況,也可以使用PHP的 getrusage()獲取CPU使用情況,該方法在windows下不可用。

print_r(getrusage());

/* 輸出

Array

(

[ru_oublock] => 0

[ru_inblock] => 0

[ru_msgsnd] => 2

[ru_msgrcv] => 3

[ru_maxrss] => 12692

[ru_ixrss] => 764

[ru_idrss] => 3864

[ru_minflt] => 94

[ru_majflt] => 0

[ru_nsignals] => 1

[ru_nvcsw] => 67

[ru_nivcsw] => 4

[ru_nswap] => 0

[ru__usec] => 0

[ru__sec] => 0

[ru__usec] => 6269

[ru__sec] => 0

)

*/

這個結構看上出很晦澀,除非你對CPU很瞭解。下面一些解釋:

ru_oublock: 塊輸出操作

ru_inblock: 塊輸入操作

ru_msgsnd: 傳送的message

ru_msgrcv: 收到的message

ru_maxrss: 最大駐留集大小

ru_ixrss: 全部共享記憶體大小

ru_idrss:全部非共享記憶體大小

ru_minflt: 頁回收

ru_majflt: 頁失效

ru_nsignals: 收到的訊號

ru_nvcsw: 主動上下文切換

ru_nivcsw: 被動上下文切換

ru_nswap: 交換區

ru__usec: 使用者態時間 (microseconds)

ru__sec: 使用者態時間(seconds)

ru__usec: 系統核心時間 (microseconds)

ru__sec: 系統核心時間?(seconds)

要看到你的指令碼消耗了多少CPU,我們需要看看“使用者態的時間”和“系統核心時間”的值。秒和微秒部分是分別提供的,您可以把微秒值除以100萬,並把它新增到秒的值後,可以得到有小數部分的秒數。

// sleep for 3 seconds (non-busy)

sleep(3);

$data = getrusage();

echo “User time: “.

($data['ru__sec'] +

$data['ru__usec'] / 1000000);

echo “System time: “.

($data['ru__sec'] +

$data['ru__usec'] / 1000000);

/* 輸出

User time: 0.011552

System time: 0

*/

是不佔用系統時間的,我們可以來看下面的一個例子:

// loop 10 million times (busy)

for($i=0;$i<10000000;$i++) {

}

$data = getrusage();

echo “User time: “.

($data['ru__sec'] +

$data['ru__usec'] / 1000000);

echo “System time: “.

($data['ru__sec'] +

$data['ru__usec'] / 1000000);

/* 輸出

User time: 1.424592

System time: 0.004204

*/

這花了大約14秒的CPU時間,幾乎所有的都是使用者的時間,因為沒有系統呼叫。傳統時間是CPU花費在系統呼叫上的上執行核心指令的時間。下面是一個例子:

$start = microtime(true);

// keep calling microtime for about 3 seconds

while(microtime(true) – $start < 3) {

}

$data = getrusage();

echo “User time: “.

($data['ru__sec'] +

$data['ru__usec'] / 1000000);

echo “System time: “.

($data['ru__sec'] +

$data['ru__usec'] / 1000000);

/* prints

User time: 1.088171

System time: 1.675315

*/

我們可以看到上面這個例子更耗CPU。

  5、獲取系統常量

PHP 提供非常有用的系統常量 可以讓你得到當前的行號 (__LINE__),檔案 (__FILE__),目錄 (__DIR__),函式名 (__FUNCTION__),類名(__CLASS__),方法名(__METHOD__) 和名字空間 (__NAMESPACE__),很像C語言

我們可以以為這些東西主要是用於除錯,當也不一定,比如我們可以在include其它檔案的.時候使用?__FILE__ (當然,你也可以在 PHP 5.3以後使用 __DIR__ ),下面是一個例子。

// this is relative to the loaded script’s path

// it may cause problems when running scripts from different directories

require_once(‘config/’);

// this is always relative to this file’s path

// no matter where it was included from

require_once(dirname(__FILE__) . ‘/config/’);

複製程式碼

下面是使用 __LINE__ 來輸出一些debug的資訊,這樣有助於你除錯程式:

// some code

// …

my_debug(“some debug message”, __LINE__);

/* 輸出

Line 4: some debug message

*/

// some more code

// …

my_debug(“another debug message”, __LINE__);

/* 輸出

Line 11: another debug message

*/

function my_debug($msg, $line) {

echo “Line $line: $msgn”;

}

  6、生成唯一的id

很多朋友都利用md5()來生成唯一的編號,但是md5()有幾個缺點:1、無序,導致資料庫中排序效能下降。2、太長,需要更多的儲存空間。其實PHP中自帶一個函式來生成唯一的id,這個函式就是uniqid()。下面是用法:

// generate unique string

echo uniqid();

/* 輸出

4bd67c947233e

*/

// generate another unique string

echo uniqid();

/* 輸出

4bd67c9472340

*/

該演算法是根據CPU時間戳來生成的,所以在相近的時間段內,id前幾位是一樣的,這也方便id的排序,如果你想更好的避免重複,可以在id前加上字首,如:

// 字首

echo uniqid(‘foo_’);

/* 輸出

foo_4bd67d6cd8b8f

*/

// 有更多的熵

echo uniqid(”,true);

/* 輸出

4bd67d6cd8b926.12135106

*/

// 都有

echo uniqid(‘bar_’,true);

/* 輸出

bar_4bd67da367b650.43684647

*/

  7、序列化

PHP序列化功能大家可能用的比較多,也比較常見,當你需要把資料存到資料庫或者檔案中是,你可以利用PHP中的serialize() 和 unserialize()方法來實現序列化和反序列化,程式碼如下:

// 一個複雜的陣列

$myvar = array(

‘hello’,

42,

array(1,’two’),

‘apple’

);

// 序列化

$string = serialize($myvar);

echo $string;

/* 輸出

a:4:{i:0;s:5:”hello”;i:1;i:42;i:2;a:2:{i:0;i:1;i:1;s:3:”two”;}i:3;s:5:”apple”;}

*/

// 反序例化

$newvar = unserialize($string);

print_r($newvar);

/* 輸出

Array

(

[0] => hello

[1] => 42

[2] => Array

(

[0] => 1

[1] => two

)

[3] => apple

)

*/

如何序列化成json格式呢,放心,php也已經為你做好了,使用php 5.2以上版本的使用者可以使用json_encode() 和 json_decode() 函式來實現json格式的序列化,程式碼如下:

// a complex array

$myvar = array(

‘hello’,

42,

array(1,’two’),

‘apple’

);

// convert to a string

$string = json_encode($myvar);

echo $string;

/* prints

["hello",42,[1,"two"],”apple”]

*/

// you can reproduce the original variable

$newvar = json_decode($string);

print_r($newvar);

/* prints

Array

(

[0] => hello

[1] => 42

[2] => Array

(

[0] => 1

[1] => two

)

[3] => apple

)

*/

  8、字串壓縮

當我們說到壓縮,我們可能會想到檔案壓縮,其實,字串也是可以壓縮的。PHP提供了 gzcompress() 和gzuncompress() 函式:

$string =

“Lorem ipsum dolor sit amet, consectetur

adipiscing elit. Nunc ut elit id mi ultricies

adipiscing. Nulla facilisi. Praesent pulvinar,

sapien vel feugiat vestibulum, nulla dui pretium orci,

non ultricies elit lacus quis ante. Lorem ipsum dolor

sit amet, consectetur adipiscing elit. Aliquam

pretium ullamcorper urna quis iaculis. Etiam ac massa

sed turpis tempor luctus. Curabitur sed nibh eu elit

mollis congue. Praesent ipsum diam, consectetur vitae

ornare a, aliquam a nunc. In id magna pellentesque

tellus posuere adipiscing. Sed non mi metus, at lacinia

augue. Sed magna nisi, ornare in mollis in, mollis

sed nunc. Etiam at justo in leo congue mollis.

Nullam in neque eget metus hendrerit scelerisque

eu non enim. Ut malesuada lacus eu nulla bibendum

id euismod urna sodales. “;

$compressed = gzcompress($string);

echo “Original size: “. strlen($string).”n”;

/* 輸出原始大小

Original size: 800

*/

echo “Compressed size: “. strlen($compressed).”n”;

/* 輸出壓縮後的大小

Compressed size: 418

*/

// 解壓縮

$original = gzuncompress($compressed);

幾乎有50% 壓縮比率。同時,你還可以使用 gzencode() 和 gzdecode() 函式來壓縮,只不用其用了不同的壓縮演算法。