PHP的大括號(花括號{})使用詳解


一、不管什么程序,function name(){}, for(){}, ….這太多了,不說也知道什么用了。

二、$str{4}在字符串的變量的后面跟上{}大括號和中括號[]一樣都是把某個字符串變量當成數組處理。

三、{$val}這種情況就是我遇到的問題,這時候大括號起的作用就是,告訴PHP,括起來的要當成變量處理。

如下例子:

//The following is okay as it's inside a string. Constants are not
//looked for within strings so no E_NOTICE error here
print "Hello $arr[fruit]"; // Hello apple

//With one exception, braces surrounding arrays within strings
//allows constants to be looked for
print "Hello {$arr[fruit]}"; // Hello carrot
print "Hello {$arr['fruit']}"; // Hello apple

 


 

另:PHP 字符串變量中大括號(花括號{})的作用

PHP 變量后面加上一個大括號{},里面填上數字,就是指 PHP 變量相應序號的字符。

例如:

$str = 'hello';

echo $str{0}; // 輸出為 h ,也可以 $str[0]
echo $str{1}; // 輸出為 e ,也可以 $str[1]

如果要檢查某個字符串是否滿足多少長度,可以考慮用這種大括號(花括號)加 isset 的方式替代 strlen 函數,因為 isset 是語言結構,strlen 是函數,所以使用 isset 比使用 strlen 效率更高。

比如判斷一個字符串的長度是否小於 5:

if  ( !isset ( $str{5} ) ) 就比 if  ( strlen ( $str ) < 5 ) 好。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM