搜尋
首頁後端開發php教程php 常用函數收集

php 常用函數收集

Nov 22, 2016 am 10:54 AM





1、傳遞任意數量的函數參數 

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

Php程式碼 
// 兩個預設參數的函數  
function foo($arg1 = ”, $arg2 = ”) {  
echo “arg1: $arg1n”;
echo “arg2: $arg2n”;  
}  
foo('hello','world');  
/* 輸出: 
 arg1: 
arg2: 
*/  
下面這個例子是PHP的不定參數用法,使用到了?func_get_args()方法:  
// 是的,形蠔/  
function foo(的傳入參數的陣列  
$args = func_get_args();  
foreach ($args as $k => $v) {  
echo “arg }  
foo();  
/* 什麼也不會輸出*/  
foo('hello');  
/* 輸出 
arg1: hello 
*/ ;  
/* 輸出 
arg1: hello 
arg2: world 
arg3: again 
*/  


2、使用glob()來找出文件名詞
當你看到?glob() 的時候,你也許並不知道這是用來做什麼的,其實glob()和scandir() 一樣,可以用來查找文件,請看下面的用法: 

Php程式碼
// 取得所有的字尾為PHP的檔案  
$files = glob('*.php');  
print_r($files);  
/* 輸出: 
Array test
(0. [1] => pi.php 
[2] => post_output.php 
[3] => test.php 

*/  

?取PHP檔案與TXT檔  
$files = glob('*.{php,txt}', GLOB_BRACE);  
print_r($files);  
/*輸出: 
Array 
(
[1] => pi.php 
[2] => post_output.php 
[3] => test.php 
[4] => log.txt 
[5] => test.txt 


*


你還可以加上路徑: 

Php代碼 
$files = glob('../images/a*.jpg');  
print_r($ [0] => ../images/apple.jpg 
[1] => ../images/art.jpg 

*/  


如果你想要得到絕對路徑,可以呼叫?real() 函數:

Php程式碼 
$files = glob('../images/a*.jpg');  
// applies the function to each array element  
$files = array_map('real)($files); $files);  
/* output looks like: 
Array 

[0] => C:wampwwwimagesapple.jpg 
[1] => C:wampimagesart.jpgapple.jpg 
[1] => C:wampimagesart.jpgg 狀況資訊 

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

Php代碼 
echo “Initial: “.memory_get_usage().” bytes n”;  
/* 輸出 
Initial: 361400 bytes */ i $array []= md5($i);  
}  
// 刪除一半的記憶體  
for ($i = 0; $i }  
echo “Final: “.memory_get_usage().” bytes n”;  
/* prints 
Final: 885912 by
/* prints 
Final: 885912 bybytes at. bytes n”;  
/* 輸出峰值 
Peak: 13687072 bytes 
*/  


4、取得CPU使用資訊 



4、取得CPU使用資訊 

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

Php程式碼 
print_r(getrusage());  
/* 輸出 
Array 

[ru_oublock] => 0 
[ru_inblock] = 2 3 
[ ru_maxrss] => 12692 
[ru_ixrss] => 764 
[ru_idrss] => 3864 
[ru_minflt] => 94 
[ru_majflt] = 0 67 
[ru_nivcsw ] => 4 
[ru_nswap] => 0 
[ru_utime.tv_usec] => 0 
[ru_utime.tv_sec] => 0 
[ru_stime.tv_secc] => 6269. */  


這個結構看起來很晦澀,除非你對CPU很了解。以下一些解釋: 

ru_oublock: 區塊輸出操作 
ru_inblock: 區塊輸入操作 
ru_msgsnd: 傳送的message 
ru_msgrrs全部非共享記憶體大小 
ru_minflt: 頁回收 
ru_majflt: 頁失效 
ru_nsignals: 收到的訊號 
ru_nvcsw: 主動情境切換 
ru_nivcs:sectimes:cLow_Lam; 
ru_utime .tv_sec: 使用者態時間(seconds) 
ru_stime.tv_usec: 系統核心時間(microseconds) 
ru_stime.tv_sec: 系統核心時間?(seconds) 

要看到你的腳本消耗了多少CPU,我們需要看看「什麼」
要看到你的腳本消耗了多少使用者態的時間」和「系統核心時間」的值。秒和微秒部分是分別提供的,您可以將微秒值除以100萬,並把它加到秒的值後,可以得到有小數部分的秒數。

Php代碼 
// sleep for 3 seconds (non-busy)  
sleep(3);  
$data = getrusage();  
echo “Usertime:s:. o.
$data['ru_utime.tv_usec'] / 1000000);  
echo “System time: “.  
($data['ru_stime.tv_sec'] + ']
($data['ru_stime.tv_sec'] + ')
$data['ru_sL_stime.tv * 輸出 
User time: 0.011552 
System time: 0 
*/  


sleep是不佔用系統時間的,我們可以來看下面的一個例子:? for($i=0;$i}  
$data = getrusage();  
echo “User time: “.  
($data['ru
echo “User time: “.  
($data['ru_time.tv_sec.] 'ru_utime.tv_usec'] / 1000000);  
echo “System time: “.  
($data['ru_stime.tv_sec'] +  
$data['ru_stime.tv_usec'] / time: 1.424592 
System time: 0.004204 
*/  


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

Php代碼 
$start = microtime(true);  
// keep calling microtime for about 3 seconds  
}while(microtime(true) – $start }while(microtime(true) – $start echo “User time: “.  
($data['ru_utime.tv_sec'] +  
$data['ru_utime.tv_usec'] / 1000000); ru_stime.tv_sec'] +  
$data['ru_stime.tv_usec'] / 1000000);  
/* prints 
User time: 1.088171 
System time:
我們可以看到上面這個範例更耗CPU 。

5、取得系統常數 

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

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

Php程式碼 
// this is relative to the loaded script’s path  
// it may cause problems when running scripts from different directories 
.// this is always relative to this file's path  
// no matter where it was included from  
require_once(dirname(__FILE__) . '/config/database.php'); 🠎的訊息,這樣有助於你偵錯程式: 

Php代碼 
// some code  
// …  
my_debug(“some debug message”, __LINE__o🠟/some
/ 是 m
// some more code  
// …  
my_debug(“another debug message”, __LINE__);  
/* 輸出 
Line 11: another demmm demido_o​​iono_m.
echo “ Line $line: $msgn”;  
}  


6、產生唯一的id 

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

Php代碼 
// generate unique string  
echo uniqid();  
/* 輸出 
4bd67c947233e uniqid();  
/* 輸出 
4bd67c9472340 
* /  


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

Php代碼 
// 前綴  
echo uniqid('foo_');  
/* 輸出 
f id(”,true);
/* 輸出 
4bd67d6cd8b926.12135106 
*/  
// 都有  
echo uniqid('bar_',true);   
echo uniqid('bar_',true);   
*/  


7、序列化 

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

Php代碼 
// 一個複雜的陣列  
$myvar = array(  
'hello',  
42,  
array(1,',  
42,  
array(1,'swo'),app  );  
$ 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 
[0] => hello 
[1] => 42 
[0] 1 
[1] => two 

[3] => apple 

*/  


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

Php程式碼 
// a complex array  
$myvar = array( 
'hello', 
$myvar 'two'),  
'apple'  
);  
// convert to a string  
$string = json_encode($myvar);  
echo $string two"],”apple”] 
*/  
// you can reproduce the original variable  
$newvar = json_decode($string);  
print_r($newvar = json_decode($string);  
print_r($newvar); > hello 
[1] => 42 
[2] => Array 

[0] => 1 
[1] => two 

[3] => apple 、字串壓縮 

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

Php代碼 
$string =  
「Lorem ipsum dolor sit amet, consectetur  
adipiscing . Praesent pulvinar,  
sapien vel feugiat vestibulum, nulla dui pretium orci,  
non ultricies elit lacus quis ante. Lorem ipsum dolor  
遵循輔導流程很重要。一些價格對ullamcorper骨灰盒的人來說是有針對性的。即使與群眾同在,但哀悼的醜陋時刻。 Curabitur sed nibh eu elit
軟作業。它就是家,是生命的結果。在那些大孩子們
告訴我們要進行輔導。但不是我的恐懼,而是 Lacinia
augue。但很好,除非,以軟的方式裝飾,軟的
但是現在。而且,正好趕上做作業。  
Nulla 也不需要害怕 Hendrerit scelerisque
eu 不需要。果然沒有euismod湖可以喝。 “;  
$壓縮= gzcompress($string);  
echo“原始尺寸:”。 strlen($string)."n";  
/* 輸出原始大小
原始大小:800
*/
echo “壓縮後大小:」。strlen($壓縮). 」n”;  
/* 解光劇後後圖片
壓縮大小: 418
*/ 
// 解光劇 
$original = gzuncompress($compressed);有50% 的壓縮率,同時還可以使用?gzencode() 和gzdecode() 函數來壓縮,只是使用不同的壓縮演算法,是不是很實用? >

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
高流量網站的PHP性能調整高流量網站的PHP性能調整May 14, 2025 am 12:13 AM

TheSecretTokeEpingAphp-PowerEdwebSiterUnningSmoothlyShyunderHeavyLoadInVolvOLVOLVOLDEVERSALKEYSTRATICES:1)emplactopCodeCachingWithOpcachingWithOpCacheToreCescriptexecution Time,2)使用atabasequercachingCachingCachingWithRedataBasEndataBaseLeSendataBaseLoad,3)

PHP中的依賴注入:初學者的代碼示例PHP中的依賴注入:初學者的代碼示例May 14, 2025 am 12:08 AM

你應該關心DependencyInjection(DI),因為它能讓你的代碼更清晰、更易維護。 1)DI通過解耦類,使其更模塊化,2)提高了測試的便捷性和代碼的靈活性,3)使用DI容器可以管理複雜的依賴關係,但要注意性能影響和循環依賴問題,4)最佳實踐是依賴於抽象接口,實現鬆散耦合。

PHP性能:是否可以優化應用程序?PHP性能:是否可以優化應用程序?May 14, 2025 am 12:04 AM

是的,優化papplicationispossibleandessential.1)empartcachingingcachingusedapcutorediucedsatabaseload.2)優化的atabaseswithexing,高效Quereteries,and ConconnectionPooling.3)EnhanceCodeWithBuilt-unctions,避免使用,避免使用ingglobalalairaiables,並避免使用

PHP性能優化:最終指南PHP性能優化:最終指南May 14, 2025 am 12:02 AM

theKeyStrategiestosigantificallyBoostPhpaPplicationPerformenCeare:1)UseOpCodeCachingLikeLikeLikeLikeLikeCacheToreDuceExecutiontime,2)優化AtabaseInteractionswithPreparedStateTementStatementStatementAndProperIndexing,3)配置

PHP依賴注入容器:快速啟動PHP依賴注入容器:快速啟動May 13, 2025 am 12:11 AM

aphpdepentioncontiveContainerIsatoolThatManagesClassDeptions,增強codemodocultion,可驗證性和Maintainability.itactsasaceCentralHubForeatingingIndections,因此reducingTightCightTightCoupOulplingIndeSingantInting。

PHP中的依賴注入與服務定位器PHP中的依賴注入與服務定位器May 13, 2025 am 12:10 AM

選擇DependencyInjection(DI)用於大型應用,ServiceLocator適合小型項目或原型。 1)DI通過構造函數注入依賴,提高代碼的測試性和模塊化。 2)ServiceLocator通過中心註冊獲取服務,方便但可能導致代碼耦合度增加。

PHP性能優化策略。PHP性能優化策略。May 13, 2025 am 12:06 AM

phpapplicationscanbeoptimizedForsPeedAndeffificeby:1)啟用cacheInphp.ini,2)使用preparedStatatementSwithPdoforDatabasequesies,3)3)替換loopswitharray_filtaray_filteraray_maparray_mapfordataprocrocessing,4)conformentnginxasaseproxy,5)

PHP電子郵件驗證:確保正確發送電子郵件PHP電子郵件驗證:確保正確發送電子郵件May 13, 2025 am 12:06 AM

phpemailvalidation invoLvesthreesteps:1)格式化進行regulareXpressecthemailFormat; 2)dnsvalidationtoshethedomainhasavalidmxrecord; 3)

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具