leni_m
@leni_m
ЧупаКобрус

Как заставить return работать?

Написал рекурсивную функцию, которая выводит данные через echo:
function get_text($el) {
    $text = "";
    if ($el instanceof PhpOffice\PhpWord\Element\TextRun) {
        foreach ($el->getElements() as $child) {
            get_text($child);
        }
    } elseif ($el instanceof PhpOffice\PhpWord\Element\Text) {
        $text .= $el->getText();
    }
    echo $text;
}

И когда я пишу get_text($my_el); все прекрасно выводит, как мне нужно.
Но когда я вместо echo $text; пишу return $text;,
и в коде использую echo get_text($my_el); или $my_text = get_text($my_el); echo $my_text;,
то перестает что-либо выводиться. В чем проблема?
  • Вопрос задан
  • 82 просмотра
Решения вопроса 2
@supgordan
Middle PHP Developer
function get_text($el) {
    $text = "";
    if ($el instanceof PhpOffice\PhpWord\Element\TextRun) {
        foreach ($el->getElements() as $child) {
           echo get_text($child);
        }
    } elseif ($el instanceof PhpOffice\PhpWord\Element\Text) {
        $text .= $el->getText();
    }
    return $text;
}

Рекурсия потому что
Ответ написан
@entermix
function get_text($el) {
    $text = "";
    if ($el instanceof PhpOffice\PhpWord\Element\TextRun) {
        foreach ($el->getElements() as $child) {
            $text .= get_text($child);
        }
    } elseif ($el instanceof PhpOffice\PhpWord\Element\Text) {
        $text .= $el->getText();
    }
    return $text;
}
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы