• 冒险村物语
  • 英雄无敌3塔防
  • 驾考家园手游

PHP编程注意事项

2015-05-27

1、php隐性的三元操作符(?:)优先级问题:
例1:
$person = $who or $person = "laruence";  
  
//实际上是等同于:  
  
$person = emptyempty($who)? "laruence" : $who;  
 例2
$arr = array(1=>1,3=>3);  
$i = 2;  
$a = ’test‘ . isset($arr[$i]) ? $arr[$i] : $i;  
$a 是什么? 这个问题, 咋一看觉得简单, 
$a = ‘test2';
其实仔细推敲后运行的,结果是notice:Undefined index 2..
由于优先级的问题, 连接符的优先级比三元操作符高。
首先是判断 ' test'. isset($arr[$i]) 这个字符串永远是true,因此:
$a =  $arr[$i];以致php提示提醒。
 
 
2. PHP函数名和类名不区分大小写的,而变量名是区分大小写的。
所以自己写的php模块,往往是大写的问题,编译不通过。
 
3.系列化传递问题
把复杂的数据类型压缩到一个字符串中
serialize() 把变量和它们的值编码成文本形式
unserialize() 恢复原先变量
$stooges = array('Moe','Larry','Curly');  
$new = serialize($stooges);  
print_r($new);echo "<br />";  
print_r(unserialize($new));  
<span style="font-family:Arial;BACKGROUND-COLOR: #ffffff"></span>  
结果:a:3:{i:0;s:3:"Moe";i:1;s:5:"Larry";i:2;s:5:"Curly";}
Array ( [0] => Moe [1] => Larry [2] => Curly )
当把这些序列化的数据放在URL中在页面之间会传递时,需要对这些数据调用urlencode(),以确保在其中的URL元字符进行处理:
 
$shopping = array('Poppy seed bagel' => 2,'Plain Bagel' =>1,'Lox' =>4);  
echo '<a href="next.php?cart='.urlencode(serialize($shopping)).'">next</a>';  
 
margic_quotes_gpc和magic_quotes_runtime配置项的设置会影响传递到unserialize()中的数据。
如果magic_quotes_gpc项是启用的,那么在URL、POST变量以及cookies中传递的数据在反序列化之前必须用stripslashes()进行处理:
$new_cart = unserialize(stripslashes($cart)); //如果magic_quotes_gpc开启  
$new_cart = unserialize($cart);  
 
如果magic_quotes_runtime是启用的,那么在向文件中写入序列化的数据之前必须用addslashes()进行处理,而在读取它们之前则必须用stripslashes()进行处理:
$fp = fopen('/tmp/cart','w');  
fputs($fp,addslashes(serialize($a)));  
fclose($fp);  
//如果magic_quotes_runtime开启  
$new_cat = unserialize(stripslashes(file_get_contents('/tmp/cart')));  
//如果magic_quotes_runtime关闭  
$new_cat = unserialize(file_get_contents('/tmp/cart'));  
 
在启用了magic_quotes_runtime的情况下,从数据库中读取序列化的数据也必须经过stripslashes()的处理,保存到数据库中的序列化数据必须要经过addslashes()的处理,以便能够适当地存储。
mysql_query("insert into cart(id,data) values(1,'".addslashes(serialize($cart))."')");  
$rs = mysql_query('select data from cart where id=1');  
$ob = mysql_fetch_object($rs);  
//如果magic_quotes_runtime开启  
$new_cart = unserialize(stripslashes($ob->data));  
//如果magic_quotes_runtime关闭  
$new_cart = unserialize($ob->data);  
当对一个对象进行反序列化操作时,PHP会自动地调用其__wakeUp()方法。这样就使得对象能够重新建立起序列化时未能保留的各种状态。例如:数据库连接等。
 
4. 引用注意事项
PHP中引用意味着用不同的名字访问同一个变量内容,引用不是C的指针(C语言中的指针里面存储的是变量的内容,在内存中存放的地址),是变量的另外一个别名或者映射。注意在 PHP 中,变量名和变量内容是不一样的,因此同样的内容可以有不同的名字。最接近的比喻是 Unix 的文件名和文件本身

人气推荐

知识阅读

精彩推荐

  • 游戏
  • 软件
查看更多>>