Home > Software design >  Void as a str_replace() param in PHP 8
Void as a str_replace() param in PHP 8

Time:11-05

I'm trying to move my small project to PHP 8 and I'm struggling with an equivalent of str_replace() function.

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();
}

The problem is that in PHP 8 cannot use $view in str_replace() function and I'm getting: Expected type 'array|string'. Found 'void'

Does anyone has a solution for this?

CodePudding user response:

Without knowing exactly the other parts of your code, this is only a guess by me, but try modifying your renderOnlyView and layoutContent functions, like this:

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;
}

This should capture every echo-ed information from your Application::$ROOT_DIR."/views/$view.php" and Application::$ROOT_DIR."/views/layouts/main.php" files respectively, and return it as a string to the caller scope.

CodePudding user response:

If you set strict_types = 1 then you must pass the arguments as array so

public function renderView($view)
{
    $layoutContent = $this->layoutContent();
    $viewContent = $this->renderOnlyView($view);
    return str_replace(['{{content}}'], [$viewContent], strval($layoutContent));
}

You can read it here

  • Related