我试图了解在为变量赋值之前初始化变量的重要性,在极少数情况下,例如,您可能在循环中创建数组。
例如;
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].",";
}
我想知道为什么在这两种情况下,建议在向变量分配数据之前对其进行初始化?或者事实并非如此,我只是听错了。此规则是否存在异常(exception)情况(如果存在)?
更新:这是在此函数中初始化变量的正确方法吗?
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;
}
或者在 $content_index
、$src_index
和 $ 等变量前使用
,并在将包含的单独文件中初始化它们,即 global
关键字会更谨慎吗? alt_indexinit_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/