PHP unset函數(shù)原理及使用方法解析
unset—釋放給定的變量
說明
unset(mixed$var[,mixed$...] ) :void
unset()銷毀指定的變量。
unset()在函數(shù)中的行為會(huì)依賴于想要銷毀的變量的類型而有所不同。
如果在函數(shù)中unset()一個(gè)全局變量,則只是局部變量被銷毀,而在調(diào)用環(huán)境中的變量將保持調(diào)用unset()之前一樣的值。
<?php function destroy_foo() { global $foo; unset($foo); } $foo = ’bar’; destroy_foo(); echo $foo; ?>
以上例程會(huì)輸出:
bar
如果您想在函數(shù)中unset()一個(gè)全局變量,可使用$GLOBALS數(shù)組來實(shí)現(xiàn):
<?php function foo() { unset($GLOBALS[’bar’]); } $bar = 'something'; foo(); ?>
如果在函數(shù)中unset()一個(gè)通過引用傳遞的變量,則只是局部變量被銷毀,而在調(diào)用環(huán)境中的變量將保持調(diào)用unset()之前一樣的值。
<?php function foo(&$bar) { unset($bar); $bar = 'blah'; } $bar = ’something’; echo '$barn'; foo($bar); echo '$barn'; ?>
以上例程會(huì)輸出:
somethingsomething
如果在函數(shù)中unset()一個(gè)靜態(tài)變量,那么在函數(shù)內(nèi)部此靜態(tài)變量將被銷毀。但是,當(dāng)再次調(diào)用此函數(shù)時(shí),此靜態(tài)變量將被復(fù)原為上次被銷毀之前的值。
<?php function foo() { static $bar; $bar++; echo 'Before unset: $bar, '; unset($bar); $bar = 23; echo 'after unset: $barn'; } foo(); foo(); foo(); ?>
以上例程會(huì)輸出:
Before unset: 1, after unset: 23Before unset: 2, after unset: 23Before unset: 3, after unset: 23
參數(shù)
var
要銷毀的變量。
...
其他變量……
返回值
沒有返回值。
范例
Example #1unset()示例
<?php // 銷毀單個(gè)變量 unset ($foo); // 銷毀單個(gè)數(shù)組元素 unset ($bar[’quux’]); // 銷毀一個(gè)以上的變量 unset($foo1, $foo2, $foo3); ?>
Example #2 使用(unset)類型強(qiáng)制轉(zhuǎn)換
(unset)類型強(qiáng)制轉(zhuǎn)換常常和函數(shù)unset()引起困惑。 為了完整性,(unset)是作為一個(gè)NULL類型的強(qiáng)制轉(zhuǎn)換。它不會(huì)改變變量的類型。
<?php $name = ’Felipe’; var_dump((unset) $name); var_dump($name); ?>
以上例程會(huì)輸出:
NULLstring(6) 'Felipe'
注釋
Note:因?yàn)槭且粋€(gè)語言構(gòu)造器而不是一個(gè)函數(shù),不能被可變函數(shù)調(diào)用。 It is possible to unset even object properties visible in current context. 在 PHP 5 之前無法在對(duì)象里銷毀$this。 在unset()一個(gè)無法訪問的對(duì)象屬性時(shí),如果定義了__unset()則對(duì)調(diào)用這個(gè)重載方法。以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. JSP+Servlet實(shí)現(xiàn)文件上傳到服務(wù)器功能2. asp讀取xml文件和記數(shù)3. JSP之表單提交get和post的區(qū)別詳解及實(shí)例4. 低版本IE正常運(yùn)行HTML5+CSS3網(wǎng)站的3種解決方案5. jsp+servlet實(shí)現(xiàn)猜數(shù)字游戲6. 將properties文件的配置設(shè)置為整個(gè)Web應(yīng)用的全局變量實(shí)現(xiàn)方法7. UDDI FAQs8. ASP常用日期格式化函數(shù) FormatDate()9. HTML <!DOCTYPE> 標(biāo)簽10. CSS可以做的幾個(gè)令你嘆為觀止的實(shí)例分享
