PHP/TP一些避免使用的用法

1 避免一個預定義變量賦給多處。如果是string類型,會過濾掉所有錯誤的過濾條件。
見以下代碼的輸出
public function testSql()
	{
		$fileID = array("dbc", null);
		$loginID = "";
		$result = M("user")->where("userID='%s' or email='%s'", $loginID)->find();
		echo M()->getLastSql() . "<br>";
		
		$resutl2 = M("file")->where("filekey=%d or fileID=%d", $fileID)->find();
		echo M()->getLastSql() . "<br>";
		
		$data['fileID'] = array("in", $fileID);
		$result = D("File")->where($data)->find();
		echo M()->getLastSql() . "<br>";
	}


輸出
SELECT * FROM `user` LIMIT 1
SELECT * FROM `file` WHERE ( filekey=0 or fileID=0 ) LIMIT 1
SELECT * FROM `file` WHERE ( `fileID` IN ('dbc',null) ) LIMIT 1 


如果是%s,則會把where條件都過濾掉了,可能造成很驗證的後果。

2 數組遍歷的引用問題
若數組遍歷使用了引用,當再次遍歷該數組的時候,不要用同樣的變量名。否則最後一個數組的值會被倒數第二個覆蓋掉。
解決辦法:變量名不要重複,換一個新的變量。
foreach ($issueData as $p => &$issue) {
				if (!$issue['hidden'] && $issue['price'] && (int)($issue['price']) === 0) {
					$issue['access'] = TRUE;
				} elseif ($userData) {
					$issueID = $issue['issueID'];
					$issue["access"] = $userData[$issueID] ? true : false;
				} else {
					$issue["access"] = FALSE;
				}
			}

$responseData = array();
		foreach ($issueData as $i => $issue) {
			if ($issue['hidden']) {
				if ($userToken && $issue['access']) {
					$responseData[] = $issue;
				}
			} else {
				$responseData[] = $issue;
			}
		}


修改後的code
foreach ($issueData as $p => &$issue) {
				if (!$issue['hidden'] && $issue['price'] && (int)($issue['price']) === 0) {
					$issue['access'] = TRUE;
				} elseif ($userData) {
					$issueID = $issue['issueID'];
					$issue["access"] = $userData[$issueID] ? true : false;
				} else {
					$issue["access"] = FALSE;
				}
			}
$responseData = array();
		foreach ($issueData as $i => $item) {
			if ($item['hidden']) {
				if ($userToken && $item['access']) {
					$responseData[] = $item;
				}
			} else {
				$responseData[] = $item;
			}
		}


測試代碼
 $data=array();
$arr=array("abc","efg");
$arr2=array("rtrt","yyy");
foreach ($arr as $k => &$v) {
$v=$v.$k;
}
print_r($arr);


foreach ($arr2 as $k => $v) {
$data[]=$v;
}
print_r($data);
print_r($arr);


輸出
Array ( [0] => abc0 [1] => efg1 ) Array ( [0] => abc0 [1] => abc0 ) Array ( [0] => abc0 [1] => abc0 ) 

你可能感兴趣的:(編碼規範)