PHP 7.2在第一个字节传输到客户端之前自动执行回调

时间:2018-09-19 01:36:12

标签: php

PHP 7.2: 有没有办法在发送到客户端的第一个字节之前强制“自动”调用php函数?
(HTML标记或其他任何东西) 例如:songs.php

// Please ignore spelling mistakes, and work on concept alone.
require_once('sessionSetup.php');
require_once('setup_Pre_HTML_Tag_Transmission_Enforcer.php');
// The above has a function called: doMyHTMLTags();

doMyStuff(); // Setups, validations
doMoreStuff();
doHTMLContentDisplay();

// I need to execute doMyHTMLTags(), if and when any of the functions starts sending out displayable text.

示例:如果doMoreStuffDIE('No resources');或者,如果doMyStuff执行了{ echo 'unexpected issue'; exit; },,我仍然需要执行我的doMyHTMLTags()

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

没有尝试过,但是也许ob_start可以达到目的:

ob_start(
    function($buffer) {
        // nothing was produced
        if (strlen($buffer) === 0) {
            return false;
        }

        // prepend our string
        return doMyHTMLTags() . $buffer;
    }
);

doMyStuff(); // Setups, validations
doMoreStuff();
doHTMLContentDisplay();

如果doMyHTMLTags()不返回字符串,但正在将其打印到浏览器中,则可以尝试执行此操作(但它将始终调用doMyHTMLTags):

// get our string from output
ob_start();
doMyHTMLTags();
$my_html_tags = ob_get_clean();

ob_start(
    function($buffer) use ($my_html_tags) {
        // nothing was produced
        if (strlen($buffer) === 0) {
            return $buffer;
        }

        // prepend our string
        return $my_html_tags . $buffer;
    }
);

doMyStuff(); // Setups, validations
doMoreStuff();
doHTMLContentDisplay();