猿问

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

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


现在它起作用了,因为我一直在使用在小部件文件中创建的变量。但是现在我尝试使用一些“全局”变量并且它没有看到它。


“全局”是指我定义的全局变量(不是 phps),例如 $dic,它是字典类的对象。


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


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


全局变量:


$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)) ?>

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


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


Tools::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>


翻过高山走不出你
浏览 232回答 1
1回答

湖上湖

我用 $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") ?>所以我想我有一些关于变量范围主题的阅读。再次感谢Magnus Eriksson,非常有帮助。
随时随地看视频慕课网APP
我要回答