【问题标题】:PHP templating and variable scopePHP模板和变量范围
【发布时间】:2016-11-25 22:42:05
【问题描述】:

我正在尝试找到一种将非全局变量传递给包含文档的方法。

page1.php

function foo()
{
   $tst =1;
   include "page2.php";
}

page2.php

echo $tst;

如何使该变量可见?以及我将如何做这个 php 模板,以便我可以拆分 html 页面的页眉正文和页脚。就像在 wordpress 中一样,它具有自定义 wp 功能,但我没有看到它们声明外部文件来使用它们。

非常感谢。

【问题讨论】:

  • page2.php 必须包含page1.php,而不是反过来或只使用会话变量

标签: php model-view-controller templating


【解决方案1】:

我认为您并不完全了解正在发生的事情。第 1 页可能应该在做回声。因此,您包含第 2 页,并且 foo 函数现在可用。您需要调用它才能真正执行。使用 global 关键字将全局变量带入函数范围。然后你可以回显它。

第 1 页:

include "page2.php";
foo();
echo $test;

第 2 页:

function foo()
{
    global $test;
    $test =1;

}

【讨论】:

    【解决方案2】:

    当函数中的变量不是全局变量时,它们在它们之外是看不到的。但是应该在第二个文件中看到函数中的包含。

    $test="Big thing";
    echo "before testFoo=".$test;
    
    // now call the function testFoo();
    
    testFoo();
    
    echo "after testFoo=".$test;
    Result : *after testFoo=Big thing*
    
    function testFoo(){
    
      // the varuiable $test is not known in the function as it's not global
    
      echo "in testFoo before modification =".$test;
    
      // Result :*Notice: Undefined variable: test in test.php 
      // in testFoo before modification =*
    
      // now inside the function define a variable test. 
    
      $test="Tooo Big thing";
      echo "in testFoo before include =".$test;
    
      // Result :*in testFoo before include =Tooo Big thing*
    
      // now including the file test2.php
    
      include('test2.php');
    
      echo "in testFoo after include =".$test;
    
      // we are still in the function testFoo() so we can see the result of   test2.php
     //  Result :in testFoo after include =small thing
    
      }
    

    在 test2.php 中

    echo $test;
    /* Result : Tooo Big thing
       as we are still in testFoo() we know $test
       now modify $test
     */
    $test = "small thing";
    

    我希望这能让事情更清楚。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-16
      • 1970-01-01
      • 2014-06-27
      • 1970-01-01
      • 2013-05-26
      • 2012-06-24
      相关资源
      最近更新 更多