9個必須知道的實用PHP函數和功能_PHP教程

來源:互聯網
上載者:User
即使使用 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('../images/a*.jpg');

print_r($files);
/* output looks like:
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:\wamp\www\images\apple.jpg
[1] => C:\wamp\www\images\art.jpg
)
*/

  • 共5頁:
  • 上一頁
  • 1
  • 2
  • 3
  • 4
  • 5
  • 下一頁

http://www.bkjia.com/PHPjc/364604.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/364604.htmlTechArticle即使使用 PHP 多年,也會偶然發現一些未曾瞭解的函數和功能。其中有些是非常有用的,但沒有得到充分利用。並不是所有人都會從頭到尾一...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.