E
E
Evgeny Yakushov2020-04-15 22:09:55
PHP
Evgeny Yakushov, 2020-04-15 22:09:55

Why doesn't ob_start see the class variable in the callback?

The problem is this, I want to add styles and scripts to the head before sending the content, the logic is simple, I do:

str_replace('</head>', $this->links. '</head>', $buffer);

But he does not see the class variable if you manually enter something like:
str_replace('</head>', '<script type="text/javascript" src="/js/jquery.js"></script></head>', $buffer);

That's all ok. Everything is OK in the variable, if you dump it, then there are styles and scripts, but it doesn’t work in callback :c

Class for processing:
class GeneralClass
{
  private $links;

  function __construct() {
    ob_start(array('self', 'pageAssembly'));
  }

  public function includeComponent($name, $template)
  {
    if ($template === "") $template = "default";

    $defPath = "/core/components/";

    $this->links .= '<link rel="stylesheet" href="' . $defPath . $name . '/templates/' . $template . '/style.css">';
    $this->links .= '<script type="text/javascript" src="' . $defPath . $name . '/templates/' . $template . '/script.js"></script>';

    include_once $defPath . $name . "/templates/" . $template . "/template.php";
  }

  private function pageAssembly($buffer) {
    return str_replace('</head>', $this->links. '</head>', $buffer);
  }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Yakushov, 2020-04-16
@yevgenyyakushov

Krch, fixed. This thing works ONLY with static data, callback in ob_start sees only static data...
A few hours to find out... I didn't find the behavior of callback in ob_start anywhere in the documentation.
Here's how it works:

class GeneralClass
{
  static private $links;

  function __construct() {
    ob_start(array("self", "pageAssembly"));
  }

  public function includeComponent($name, $template)
  {
    if ($template === "") $template = "default";

    $defPath = "/core/components/";

    self::$links .= '<link rel="stylesheet" href="' . $defPath . $name . '/templates/' . $template . '/style.css">';
    self::$links .= '<script type="text/javascript" src="' . $defPath . $name . '/templates/' . $template . '/script.js"></script>';

    include_once $defPath . $name . "/templates/" . $template . "/template.php";
  }

  public function pageAssembly($buffer) {
    return str_replace('</head>', self::$links . '</head>', $buffer);
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question