我正在尝试将我的小项目移到PHP8中,并且正在与类似于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();
}问题是PHP8不能在$view函数中使用str_replace(),我得到:Expected type 'array|string'. Found 'void'
有人有办法解决这个问题吗?
发布于 2021-11-05 08:36:45
在不完全了解代码的其他部分的情况下,这只是我的猜测,但是尝试修改renderOnlyView和layoutContent函数,如下所示:
public function renderView($view)
{
$layoutContent = $this->layoutContent();
$viewContent = $this->renderOnlyView($view);
return str_replace('{{content}}', $viewContent, $layoutContent);
}
protected function layoutContent()
{
ob_start();
include_once Application::$ROOT_DIR."/views/layouts/main.php";
$out = ob_get_clean();
return $out;
}
protected function renderOnlyView($view)
{
ob_start();
include_once Application::$ROOT_DIR."/views/$view.php";
$out = ob_get_clean();
return $out;
}这将分别从您的echo和Application::$ROOT_DIR."/views/layouts/main.php"文件中捕获每个Application::$ROOT_DIR."/views/$view.php" -ed信息,并将其作为字符串返回到调用方范围。
发布于 2021-11-05 08:47:01
如果您设置了strict_types = 1,那么必须将参数作为数组传递
public function renderView($view)
{
$layoutContent = $this->layoutContent();
$viewContent = $this->renderOnlyView($view);
return str_replace(['{{content}}'], [$viewContent], strval($layoutContent));
}你可以读这里
https://stackoverflow.com/questions/69850373
复制相似问题