Pergunta

Let's say in PHP you have a class Parent:

<?php
class Parent {

    public function speak()
    {
        // Do bunch of stuff
        $output = outcomeOfAbove();
        echo $output;
    }

}

And you have a class Child:

<?php
class Child extends Parent{

    public function speak()
    {
        parent::speak();

        echo 'Hello from child';
    }

}

Now let's say that I want the content of $output in the Child speak() function, is there a way to capture the output of parent::speak(); and stop this function from echoing? Knowing that you can't change the 'Parent' class.

Foi útil?

Solução

You can use the PHP output buffering feature:

  public function speak()
  {
    ob_start();
    parent::speak();
    $parent_output = ob_get_contents();
    ob_end_clean();

    echo 'Hello from child';
  }

}

For more info, see the PHP.net manual.

Good luck ;)

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top