【问题标题】:Using a variable inside an included file from function在函数的包含文件中使用变量
【发布时间】:2012-05-21 21:21:46
【问题描述】:

我想在我的网站中包含一个 header.php 文件。我目前有以下:

header.php

<head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="<?php if(isset($depth)){echo $depth;};?>css/style.css">

functions.php

function include_layout_template($template="", $depth="")
{
    global $depth;
    include(SITE_ROOT.DS.'public'.DS.'layouts'.DS.$template);
}

index.php

<?php include_layout_template('header.php', "../"); ?>

但是 $depth 消失了,我什至无法回显 $depth;它只是空白。如何获取在 header.php 中使用的深度变量?

【问题讨论】:

  • $depth 既是全局变量又是函数include_layout_template的参数?那一定是搞砸了……

标签: php function variables include


【解决方案1】:

您的 $depth 变量正在消失,因为它首先作为参数传递,然后定义为使用全局参数。

我会举例说明:

$global = "../../"; //the variable outside
function include_layout_template($template="", $depth="")
{
    global $depth; //This will NEVER be the parameter passed to the function
    include(SITE_ROOT.DS.'public'.DS.'layouts'.DS.$template);
}
include_layout_template("header.php", "../");

要解决,只需修改深度本身以外的函数参数即可。

function include_layout_template($template="", $cDepth="") { }

【讨论】:

    【解决方案2】:

    你必须在函数调用中重命名深度变量

    function include_layout_template($template="", $my_depth="")
    {
       global $depth;
       //if need $depth = $mydepth
    

    【讨论】:

      猜你喜欢
      • 2014-07-18
      • 1970-01-01
      • 2013-05-17
      • 2013-01-22
      • 1970-01-01
      • 1970-01-01
      • 2013-01-20
      • 2018-12-23
      • 1970-01-01
      相关资源
      最近更新 更多