標籤:style blog http io ar color os 使用 sp
1、傳遞任意數量的函數參數
我們在.NET或者JAVA編程中,一般函數參數個數都是固定的,但是PHP允許你使用任意個數的參數。下面這個樣本向你展示了PHP函數的預設參數:
// 兩個預設參數的函數function foo($arg1 = ”, $arg2 = ”) { echo “arg1: $arg1\n”;echo “arg2: $arg2\n”; } 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).”: $v\n”; } } foo(); /* 什麼也不會輸出 */ foo(‘hello’); /* 輸出arg1: hello */ foo(‘hello’, ‘world’, ‘again’); /* 輸出arg1: hello arg2: world arg3: again */2、使用glob()尋找檔案
大部分PHP函數的函數名從字面上都可以理解其用途,但是當你看到?glob() 的時候,你也許並不知道這是用來做什麼的,其實glob()和scandir() 一樣,可以用來尋找檔案,請看下面的用法:
// 取得所有的尾碼為PHP的檔案$files = glob(‘*.php’); print_r($files); /* 輸出:Array ( [0] => phptest.php [1] => pi.php [2] => post_output.php [3] => test.php ) */
3、擷取記憶體使用量情況資訊
PHP的記憶體回收機制已經非常強大,你也可以使用PHP指令碼擷取當前記憶體的使用方式,調用memory_get_usage() 函數擷取當期記憶體使用量情況,調用memory_get_peak_usage() 函數擷取記憶體使用量的峰值。參考代碼如下:
echo “Initial: “.memory_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: “.memory_get_usage().” bytes \n”; /* prints Final: 885912 bytes */ echo “Peak: “.memory_get_peak_usage().” bytes \n”; /* 輸出峰值Peak: 13687072 bytes */4、擷取系統常量
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/database.php’); // this is always relative to this file’s path // no matter where it was included from require_once(dirname(__FILE__) . ‘/config/database.php’);// 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: $msg\n”; }5、產生唯一的id
很多朋友都利用md5()來產生唯一的編號,但是md5()有幾個缺點:1、無序,導致資料庫中排序效能下降。2、太長,需要更多的儲存空間。其實PHP中內建一個函數來產生唯一的id,這個函數就是uniqid()。下面是用法:
// generate unique string echo uniqid(); /* 輸出4bd67c947233e */ // generate another unique string echo uniqid(); /* 輸出4bd67c9472340 */
6、序列化
如何序列化成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 ) */
轉載自:柒捌玖零部落格
PHP常用功能和函數