【问题标题】:Variable loses its value PHP变量失去它的价值 PHP
【发布时间】:2021-09-20 05:36:00
【问题描述】:

我有下面的代码,我的变量$layout 失去了它的价值,我不知道为什么,layoutContent 只是一种获取我网站模板的方法,然后 renderOnlyView 获取应该在该模板中呈现的视图

$layout = $this->layoutContent($layoutParams);
echo ($layout);
$view = $this->renderOnlyView($view, $params);
echo ($layout);

发生错误的整个方法

public function renderView(string $view, array $params = [], array $layoutParams = [])
{
    $layout = $this->layoutContent($layoutParams);
    echo ($layout);
    $view = $this->renderOnlyView($view, $params);
    echo ($layout);

    $layout = str_replace('{{ title }}', $layoutParams['title'] ?? 'No title', $layout);
    
    return str_replace('{{ body }}', $view, $layout);
}

renderOnlyView

protected function renderOnlyView(string $view, array $params): ?string
{
    foreach ($params as $key => $param) {
        $$key = $param;
    }
    ob_start();
    $viewFilePath = Application::$ROOT_DIR . "/views/$view.blade.php";
    if (file_exists($viewFilePath))
        include_once $viewFilePath;
    else
        echo "the view <b>$view</b> is not found";

    return ob_get_clean();
}

layoutContent以防万一

public function layoutContent(array $params = [])
{
    $layout = Application::$APP->controller->layout ?? 'main';
    ob_start();
    include_once Application::$ROOT_DIR . "/views/layout/$layout.layout.php";
    $output = ob_get_clean();
    foreach ($params as $key => $param) {
        $output = str_replace('{{ ' . $key . ' }}', $param, $output);
    }

    return $output;
}

更多信息:PHP 版本:7.4.3,系统 ubuntu 20.04

【问题讨论】:

  • $viewFilePath 文件中发生了什么?如果它正在执行类似global $layout; 的操作,那么您可能会遇到问题。
  • @kmoser 我不使用全局变量,$viewFIlePath 只有我的视图文件的完整路径,我放弃了你的理论,并将我的变量布局重命名为模板仍然发生
  • PHP 不是 Java。 $this-&gt;layout 是类属性,$layout 是局部变量。它们不是同一个变量。
  • 请问$this-&gt;layout在哪里?
  • Application::$APP-&gt;controller-&gt;layout 是控制器类的属性。以$ 开头的所有其他对layout 的引用都是(不相关的)局部变量。我不是说这个问题,但我认为值得一提。

标签: php oop


【解决方案1】:

好吧,伙计们,问题找到了,我错过了一点,这个函数被调用了两次,第一次是我渲染视图时,第二次是我的视图抛出错误并捕获它并尝试显示 @ 987654321@ 再次被调用,导致 include_once 返回 null,因为它已经被包含:D

【讨论】:

    【解决方案2】:

    你错过了一点,这个函数被调用了两次,第一次是当你渲染我的视图时,第二次当你查看时抛出一个错误并在捕获它并尝试显示 renderLayout 时再次被调用,导致 include_once返回 null 因为它已经包含了 xD

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多