我试图了解初始化变量的重要性,然后再在极少数情况下(例如,您可能在循环内创建数组)为变量赋值。
例如;
foreach($var1 as $key => $val) {
$array[] = $key;
}
在此示例中,在用于包含数组之前尚未声明
$array
,虽然有人告诉我这是一种不好的做法,但我不知道为什么。建议我改为这样做;$array = array();
foreach($var1 as $key => $val) {
$array[] = $key;
}
另一个示例,当基于许多数组值构造长字符串时:
$size = count($array);
for($i = 0; $i < $size; $i++) {
$string .= $array[$i]."del".$array_2[$i].",";
}
有人告诉我应该这样做
$string = null;
$size = count($array);
for($i = 0; $i < $size; $i++) {
$string .= $array[$i]."del".$array_2[$i].",";
}
我想知道为什么在这两种情况下都建议在为其分配数据之前先初始化变量?或不是这种情况,我只是听错了。如果存在此规则,是否有例外?
更新:这是在此函数中初始化变量的正确方法吗?
function weight_index($keyword, $src, $alt, $content, $ratio='3:3:1') {
// Initialize needed variables
$content_index = ''; $src_index = ''; $alt_index = '';
// Create all four types of $keyword variations: -, _, %20, in order to search
// through $content, $alt, $src for instances.
$keyword_fmt = array('hyphen' => str_replace(' ', '-', $keyword), 'underscore' => str_replace(' ', '_', $keyword), 'encode' => urlencode($keyword), 'original' => $keyword);
// Define weight index for each instance within a searchable "haystack".
list($src_weight, $alt_weight, $content_weight) = explode(':', $ratio);
// Get the number of instances of $keyword in each haystack for all variations.
foreach($keyword_fmt as $key => $value) {
$content_index += substr_count($value, $content); // .. may generate an error as $x_index hasn't been initialized.
$src_index += substr_count($value, $src);
$alt_index += substr_count($value, $alt);
}
// Multiply each instance by the correct ratio.
$content_index = $content_index * $content_weight;
$src_index = $src_index * $src_weight;
$alt_index = $alt_index * $alt_weight;
// Total up all instances, giving a final $weight_index.
$weight_index = $content_index + $src_index + $alt_index;
return $weight_index;
}
或者更明智的做法是在诸如
global
,$content_index
和$src_index
之类的变量之前使用$alt_index
关键字,并将它们初始化在一个单独的文件中,该文件将包含在内,即init_variables.php
包含将在使用前需要初始化的所有变量,例如在这篇文章的例子中? 最佳答案
如果您要遍历的是一个空数组,会发生什么?然后,您最终将无法定义$array
或$string
,因此当某些内容尝试引用它时,您的程序会做不好的事情。
$var1 = array();
foreach($var1 as $key => $val) {
$array[] = $key;
}
foreach($array as $v) { // errors because $array isn't defined
...
}
关于php - 初始化变量的重要性?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8427028/