【发布时间】:2021-11-05 08:28:27
【问题描述】:
我正在尝试将我的小项目迁移到 PHP 8,但我正在努力使用相当于 str_replace() 的函数。
public function renderView($view)
{
$layoutContent = $this->layoutContent();
$viewContent = $this->renderOnlyView($view);
return str_replace('{{content}}', ($viewContent), strval($layoutContent));
}
protected function layoutContent()
{
ob_start();
include_once Application::$ROOT_DIR."/views/layouts/main.php";
ob_get_clean();
}
protected function renderOnlyView($view)
{
ob_start();
include_once Application::$ROOT_DIR."/views/$view.php";
ob_get_clean();
}
问题是在 PHP 8 中不能在 str_replace() 函数中使用 $view 并且我得到:Expected type 'array|string'. Found 'void'
有没有人可以解决这个问题?
【问题讨论】:
-
您的
renderOnlyView函数没有返回任何内容,并且您没有将任何内容 (void) 添加到str_replace。你到底想达到什么目的? -
所以我有一个 template.php,它包含一个页眉、导航栏、页脚,在里面我有一个
{{content}}字符串要替换为 contact-template.php 的值, home-page.php 等 -
问题是你没有将任何东西传递给 str_replace(),正如@AdamBaranyai 所说。
-
为了清楚起见,在任何 PHP 版本中,显示的代码永远不会完成您所描述的操作。
str_replace函数没有被传递任何东西,因为layoutContent和renderOnlyView都没有返回值。我投票关闭“需要调试细节”,因为如果您有在 PHP 7 中工作的代码,那不是您向我们展示的代码。可能,这段代码一直被破坏,而 PHP 8 只是在指出它方面更有帮助。