为什么不应该';t我使用shell_exec而不是输出缓冲到';包括';将文件转换为变量


Why shouldn't I use shell_exec rather than output buffering to 'include' a file into a variable?

我有一个模板,可以处理每一页上重复的各种内容。问题是,所有不同的东西都会进入模板的中间。大多数人对此很熟悉,但这里有一些伪标签作为视觉辅助:

<begin_template>
    <top_part_of_template_with_repeated_stuff>
        <!--different stuff goes here-->
    <bottom_part_of_template_with_more_repeated_stuff>
<end_template>

我知道有各种不同的方法来处理这个问题。我不喜欢这样做:

include 'top_part_of_template.html';
// output the different part
include 'bottom_part_of_template.html';

因为打开和关闭标签在单独的文档中会让我感到困扰。我目前正在做的是这样一个模板:

<template>
    <?php if (isset($different_stuff)) echo $different_stuff ?>
<more_template>

并使用输出缓冲来获得不同的东西,比如:

ob_start();
include 'different_stuff.php';
$different_stuff = ob_get_clean();
include 'template.php';

我发现了这个答案,它建议使用shell_exec。虽然我大体上理解shell_exec的作用,但我并不熟悉它的使用

$different_stuff = shell_exec('php different_stuff.php');
include 'template.php';

它确实有效,我喜欢它只是因为它是一句话而不是三句话。不过,这感觉是个坏主意(主要是因为我认为如果这是个好主意,我会看到它被更频繁地使用,这是我第一次看到它),但我对shell_exec还不够熟悉,不知道为什么。

我觉得这听起来可能有点像一个基于观点的问题,但我真的不想征求意见。我想知道不使用这种方法的客观、明显的理由。

您正在以这种方式构建一个新的shell环境和一个新PHP实例,而不是利用您的代码已经在其中运行的PHP实例。因此,这涉及到性能和内存。

许多服务器都有单独的php.ini文件用于命令行php(shell_exec调用)和基于FPM的php(大多数现代web服务器调用)。

而且,shell_exec不会返回任何错误信息,因此您将更难检测问题并进行故障排除。