ECHO语句中的PHP函数


PHP Function inside of ECHO statement

我在Wordpress:中使用以下函数

function wpstudio_doctype() {
  $content = '<!DOCTYPE html>' . "'n";
  $content .= '<html ' . language_attributes() . '>';
    echo apply_filters( 'wpstudio_doctype', $content );
}

问题是,该函数在<!DOCTYPE html>标记上方显示$content,而不是在HTML标记内部添加字符串。

我在这里做错了什么?

language_attributes()不返回属性,而是对它们进行回声处理。

// last line of language_attributes()
echo apply_filters( 'language_attributes', $output );

这意味着它将在字符串组装之前显示。您需要使用输出缓冲捕获此值,然后将其附加到字符串中。

// Not sure if the output buffering conflicts with anything else in WordPress
function wpstudio_doctype() {
  ob_start();
  language_attributes();
  $language_attributes = ob_get_clean();
  $content = '<!DOCTYPE html>' . "'n";
  $content .= '<html ' . $language_attributes . '>';
    echo apply_filters( 'wpstudio_doctype', $content );
}

只需在ECHO语句中使用get_language_attributes(),而不用输出缓冲。在这种特定情况下:

function wpstudio_doctype() {
  $content = '<!DOCTYPE html>' . "'n";
  $content .= '<html ' . get_language_attributes() . '>';
    echo apply_filters( 'wpstudio_doctype', $content );
}