繁体   English   中英

如何在php中更改打印的变量?

[英]How to change printed variable in php?

我在主文件中放置了一个子文件,但是该子文件会影响主文件中的变量。

简单的例子:

在我的代码中包含不能在回显之前。

的index.php

<?php

    $heading= "Heading";

    echo "<h1>$headeing</h1>";

    include_once('specific_data.php');

?>

Specific_data.php

$heading = "Specific Heading";

实际输出:

<h1>Heading</h1>

所需的输出:

<h1>Specific Heading</h1>

您在分配新值之前在include os之前回显该值

尝试在包含之后移动回显

 <?php

   $heading= "Heading";



   include_once('specific_data.php');

   echo "<h1>$headeing</h1>";
?>

您可以创建MVC结构

的index.php

include_once 'view.php';

$heading='custom head';

return view('specific_data.php',compact('heading'));


view.php




function view($file,$vars=[])
{

   extract($vars);
   include_once $file.'.php';

}

specific_data.php

<h1>this variable get from index and will render <?=$heading?></h1>

从浏览器执行index.php,您将看到以下代码


this variable get from index and will render custom head

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM