这是我遇到问题的函数的简化版本:
function example(&$form) {
$name = $form->getName();
foreach ($form as $sub) {
if ($sub instanceof Form) {
example($sub);
}
// need this to be the first entry of $name
echo $name;
}
}
example($this->form);
我需要一种方法来保留$name
答案 0 :(得分:2)
尝试在函数中添加另一个参数
function example(&$form, $firstFormName = null) {
$name = $form->getName();
if(is_null($firstFormName))
$firstFormName = $name;
foreach ($form as $sub) {
if ($sub instanceof Form) {
example($sub, $firstFormName);
}
}
// need this to be the first entry of $name
echo $name;
}
example($this->form);
答案 1 :(得分:1)
只需将值作为参数传递
function example(&$form, $init_name = null) {
$name = $form->getName();
if (empty($init_name)) {
$init_name = $name;
}
foreach ($form as $sub) {
if ($sub instanceof Form) {
example($sub, $init_name);
}
// current name
echo $name;
// initial name
echo $init_name;
}
}
答案 2 :(得分:0)
这些方面的东西应该可以帮到你。
$first_name = "";
foreach ($form as $sub) {
if ($first_name == "") {
$first_name = $sub;
}
// The rest of your for loop here...