PHP中9個必須知道的實用函數及功能應用

最新PHP中9個必須知道的實用函數及功能應用

以下是三零網爲大家整理的最新PHP中9個必須知道的實用函數及功能應用的文章,希望大家能夠喜歡!

即使使用 PHP 多年,也會偶然發現一些未曾瞭解的函數和功能。其中有些是非常有用的,但沒有得到充分利用。並不是所有人都會從頭到尾一頁一頁地閱讀手冊和函數參考!
1、任意參數數目的函數

你可能已經知道,PHP 允許定義可選參數的函數。但也有完全允許任意數目的函數參數的方法。以下是可選參數的例子:
 


// function with 2 optional arguments
function foo($arg1 = '', $arg2 = ''){
   
    echo "arg1: $arg1\n";
    echo "arg2: $arg2\n";
   
    }

foo('hello', 'world');
/**
 prints:
 arg1: hello
 arg2: world
 */

foo();
/**
 prints:
 arg1:
 arg2:
 */

 


 

現在讓我們看看如何建立能夠接受任何參數數目的函數。這一次需要使用 func_get_args() 函數:


// yes, the argument list can be empty
function foo(){
   
    // returns an array of all passed arguments
    $args = func_get_args();
   
    foreach ($args as $k => $v){
        echo "arg" . ($k + 1) . ": $v\n";
        }
   
    }

foo();
/**
 prints nothing
 */

foo('hello');
/**
 prints
 arg1: hello
 */

foo('hello', 'world', 'again');
/**
 prints
 arg1: hello
 arg2: world
 arg3: again
 */

 


 

2、使用 Glob() 查找文件

許多 PHP 函數具有長描述性的名稱。然而可能會很難說出 glob() 函數能做的事情,除非你已經通過多次使用並熟悉了它。可以把它看作是比 scandir() 函數更強大的版本,可以按照某種模式搜索文件。
 


// get all php files
$files = glob('*.php');

print_r($files);
/**
 output looks like:
 Array
 (
 [0] => phptest.php
 [1] => pi.php
 [2] => post_output.php
 [3] => test.php
 )
 */

 


 

 

你可以像這樣獲得多個文件:


// get all php files AND txt files
$files = glob('*.{php,txt}', GLOB_BRACE);

print_r($files);
/**
 output looks like:
 Array
 (
 [0] => phptest.php
 [1] => pi.php
 [2] => post_output.php
 [3] => test.php
 [4] => log.txt
 [5] => test.txt
 )
 */

 


 

請注意,這些文件其實是可以返回一個路徑,這取決於查詢條件:


$files = glob('../p_w_picpaths/a*.jpg');

print_r($files);
/**
 output looks like:
 Array
 (
 [0] => ../p_w_picpaths/apple.jpg
 [1] => ../p_w_picpaths/art.jpg
 )
 */

 


 

如果你想獲得每個文件的完整路徑,你可以調用 realpath() 函數:


$files = glob('../p_w_picpaths/a*.jpg');

// applies the function to each array element
$files = array_map('realpath', $files);

print_r($files);
/**
 output looks like:
 Array
 (
 [0] => C:\wamp\www\p_w_picpaths\apple.jpg
 [1] => C:\wamp\www\p_w_picpaths\art.jpg
 )
 */

轉載來自:http://www.q3060.com/list3/list117/283.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章