对初学者非常有用的PHP技巧
13
14
15
16
17
18
function add_to_cart($item_id , $qty)
{
if(!is_array($item_id))
{
$_SESSION['cart'][$item_id] = $qty;
}
else
{
foreach($item_id as $i_id => $qty)
{
$_SESSION['cart'][$i_id] = $qty;
}
}
}
add_to_cart( 'IPHONE3' , 2 );
add_to_cart( array('IPHONE3' => 2 , 'IPAD' => 5) );
好了,现在同样的函数就可以接受不同类型的输出了。以上代码可以应用到很多地方让你的代码更加灵活。
6.省略结束的php标签,如果它是脚本中的最后一行
我不知道为什么很多博客文章在谈论php小技巧时要省略这个技巧。
?
1
2
3
4
5
echo "Hello";
//Now dont close this tag
这可以帮助你省略大量问题。举一个例子:
类文件super_class.php
?
1
2
3
4
5
6
7
8
9
10
class super_class
{
function super_function()
{
//super code
}
}
?>
//super extra character after the closing tag
现在看index.php
?
1
2
3
require_once('super_class.php');
//echo an image or pdf , or set the cookies or session data
你会得到发送错误的Header。为什么呢?因为“超级多余字符”,所有标题都去处理这个去了。于是你得开始调试。你可能需要浪费很多时间来寻找超级额外的空间。
因此要养成省略结束标签的习惯:
?
1
2
3
4
5
6
7
8
9
10
class super_class
{
function super_function()
{
//super code
}
}
//No closing tag
这样更好。
7.在一个地方收集所有输出,然后一次性输出给浏览器
这就是所谓的输出缓冲。比方说,你从不同的函数得到像这样的内容:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function print_header()
{
echo "
Site Log and Login links
";}
function print_footer()
{
echo "
";}
print_header();
for($i = 0 ; $i < 100; $i++)
{
echo "I is : $i
';
}
print_footer();
其实你应该先在一个地方收集所有输出。你可以要么将它存储于函数中的变量内部,要么使用ob_start和ob_end_clean。所以,现在应该看起来像这样
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function print_header()
{
$o = "
Site Log and Login links
";return $o;
}
function print_footer()
{
$o = "
Site was made by me
";return $o;
}
echo print_header();
for($i = 0 ; $i < 100; $i++)
{