虽然我在php中按类包含文件,但文件看不到任何变量 - 就像它们不存在一样

我已经为“创建”小部件创建了类。你调用静态函数,传递变量,并有你的甜蜜小部件。


现在它有效,因为我一直在使用在小部件文件中创建的变量。但现在我试图使用一些“全局”变量,但它没有看到它。


通过“全局”,我的意思是我定义的全局变量(不是phps),就像$dic它是字典类的对象。


为什么?我真的不想在每个小部件中创建这些变量。


我想这是因为我正在创建临时文件。(我需要用实际的标题替换,所以我得到小部件代码,替换标题,用替换的tiltle创建新的tmp文件并包含这个,然后删除){{ title }}


全局变量:


$dic = new Dictionary(isset($_COOKIE["language"]) ? htmlspecialchars($_COOKIE["language"]) : _LANG); // THE GLOBAL VARIABLE

小部件代码:


<span>{{ title }}</span>

<form action="<?php echo Path::GetCurrentURL(); ?>" method="post">

  <?php // for some reason it doesn't see any global variables so you have to create then once more in widgets which drives me nuts ugh?>

   <input type="submit" name="logoutAdm" value="<?php $dic->Translate("Log out"); ?>">

</form>

包含功能:


{

      $path = Path::Widgets("ShopPanelTitle.php");

      if (file_exists($path)) {

        $widget = file_get_contents($path);

        $widget = str_replace("{{ title }}", $title, $widget);

        $pathTmp = Tools::TMPName(".php",Path::TMP(""));

        echo $pathTmp;

        $file = fopen($pathTmp, "w+");

        fwrite($file,$widget);

        fclose($file);

        // for some reason it doesn't see any global variables so you have to create then once more in widgets

        include $pathTmp;

        unlink($pathTmp);

      }

}

我如何调用该函数:


<?php Widgets::ShopPanelTitle($dic->Translate("Main",true)) ?>

没有更多相关的代码。如果你想看到所有使用的代码,这个问题会变得非常长,并且会因为泄露公司机密而被起诉:/。


路径::小部件 - 返回小部件文件夹的路径


工具::TMPName - 返回随机名称


我得到的:


<span>Title</span>

<form action="currentPage.php" method="post">

</form>

我想得到什么:


<span>Title</span>

<form action="currentPage.php" method="post">

   <input type="submit" name="logoutAdm" value="Log out">

</form>


牛魔王的故事
浏览 94回答 1
1回答

慕田峪7331174

多亏了马格努斯·埃里克森的帮助,我发现我的问题是多么愚蠢。我用$title替换了我的{{title }}占位符,并注意到它工作得很好。所以问题在于范围,我必须告诉函数不要使用局部$dic变量,而是“注意”“全局”$dic。小部件代码:public static function ShopPanelTitle($title)&nbsp;{&nbsp; &nbsp;global $dic;&nbsp; &nbsp;$path = Path::Widgets("ShopPanelTitle.php");&nbsp; &nbsp;if (file_exists($path)) {&nbsp; &nbsp; &nbsp;$title = $dic->Translate($title,true);&nbsp; &nbsp; &nbsp;include $path;&nbsp; &nbsp;} else {&nbsp; &nbsp; &nbsp;Tools::JSLog("Widget file " . $path . " doesn't exist.");&nbsp; &nbsp;}&nbsp;}控件:<span><?= $title ?></span><form action="<?php echo Path::GetCurrentURL(); ?>" method="post">&nbsp; &nbsp; <input type="submit" name="logoutAdm" value="<?= $dic->Translate("Log out"); ?>"></form>小部件调用:<?php Widgets::ShopPanelTitle("Main") ?>所以我想我在变量范围的主题上有一些阅读要做。再次感谢马格努斯·埃里克森,非常乐于助人。
打开App,查看更多内容
随时随地看视频慕课网APP