为什么这样做......
$animal='';
$animal .= "You edited this animal: ";
if ($data['horse'] != $horse){
$animal .= 'Name from "'.$data['horse'].'" into "'.$horse.'"';
}
$sql = "INSERT INTO animal (animal,id) values(?,?)";
$q = $pdo->prepare($sql);
$q->execute(array($animal,$id));
(结果:“你编辑过这只动物:Mustang进入Marwari”)
......但是......
$animal='';
$animal .= "You edited this animal: ";
function animal_func($label, $orig, $edit) {
if ($orig != $edit){
$animal .= $label.' from "'.$orig.'" into "'.$edit.'"';
}
}
animal_func("Name",$data['horse'],$horse);
$sql = "INSERT INTO animal (animal,id) values(?,?)";
$q = $pdo->prepare($sql);
$q->execute(array($animal,$id));
(结果:“你编辑了这只动物:”)
......无效
答案 0 :(得分:1)
将此动物投入使用
function animal_func($label, $orig, $edit) {
$animal='';
$animal .= "You edited this animal: ";
if ($orig != $edit){
$animal .= $label.' from "'.$orig.'" into "'.$edit.'"';
}
}
animal_func("Name",$data['horse'],$horse);
或
声明
global $animal='';
$animal .= "You edited this animal: ";
答案 1 :(得分:1)
由于$ animal变量的范围。 http://php.net/manual/en/language.variables.scope.php
你需要传递$ animal var的回报: / *如果你只需要一次,外面更好* / $ animal。="你编辑了这只动物:&#34 ;;
function animal_func($label, $orig, $edit, $animal) {
if ($orig != $edit){
$animal .= $label.' from "'.$orig.'" into "'.$edit.'"';
return $animal;
}
}
$animal = animal_func("Name",$data['horse'],$horse,$animal);
您也可以这样做,也许更具可读性:
function animal_func($label, $orig, $edit, $animal) {
if ($orig != $edit) {
$animal .= $label.' from "'.$orig.'" into "'.$edit.'"';
return $animal;
}
}
$animal = "You edited this animal: ";
$animal = animal_func("Name",$data['horse'],$horse,$animal);
经过另一次阅读(这是更好的):
function animal_func($label, $orig, $edit) {
if ($orig != $edit) {
return $label.' from "'.$orig.'" into "'.$edit.'"';
}
}
$animal = "You edited this animal: ".animal_func("Name",$data['horse'],$horse);
答案 2 :(得分:1)
由于您$animal
内animal_func()
的范围仅限于该功能。
您需要做的是在$animal
中将animal_func()
作为参考变量传递。所以你的功能应该是这样的:
$animal='';
$animal .= "You edited this animal: ";
function animal_func($label, $orig, $edit, &$animal) {
if ($orig != $edit){
$animal .= $label.' from "'.$orig.'" into "'.$edit.'"';
}
}
animal_func("Name",$data['horse'],$horse, $animal);
请参阅PHP manuals了解变量范围,并在this link上通过引用传递变量。