4

With PHP's ob_start($callback), you can pass a static method as a callback like this:

class TemplateRenderer {
  function myCallback($bufferContents) {
    return 'Foobar instead of the buffer';
  }
}

ob_start(array('TemplateRenderer', 'myCallback'));

Or you can refer to an object like this:

$myTemplateRenderer = new TemplateRenderer();
ob_start(array($myTemplateRenderer, 'myCallback'));

Both of these work, but I'd like to know if I can start the output buffer from within a class method, and refer to the callback using $this

class TemplateRenderer {
  function myCallback($bufferContents) {
    return 'Foobar instead of the buffer';
  }

  function init() {
    // --- this doesn't work ----
    ob_start(array($this, 'myCallback'));
    // --- this doesn't work either ----
    ob_start(array('this', 'myCallback'));
  }
}

TemplateRenderer::init();

If it's even possible, what's the syntax for referring to a "callable" from within its own class?

DMack
  • 871
  • 2
  • 9
  • 21
  • What should `$this` be when you use `TemplateRenderer::init()` to call the function? `$this` is only set when you use `$object->method()` syntax. – Barmar May 21 '15 at 00:16

2 Answers2

3

I would follow Barmar's suggestion, but if you for whatever reason don't want to make instantiation, you can try this solution:

class TemplateRenderer {
  static function myCallback($bufferContents) {
    return 'Foobar instead of the buffer';
  }

  function init() {
    ob_start(array('self', 'myCallback'));
  }
}

TemplateRenderer::init();
Axalix
  • 2,831
  • 1
  • 20
  • 37
  • Thanks, I think this is the answer I was looking for: 'self' where I was trying 'this' and $this. I'm actually getting an error now on the dev server where I'm trying it: "Invalid callback self::myCallback, cannot access self:: when no class scope is active" but I think I'm on the right track. – DMack May 21 '15 at 17:29
1

You need to call init() using an object so that $this will be set.

$myTemplateRenderer = new TemplateRenderer();
$myTemplateRenderer->init();
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Sorry, I think my problem got lost in translation when I was trying to simplify my code sample for this thread, and mention the two use cases (static method and object method). Either way, I tried it again this morning and the object style did work with $this – DMack May 21 '15 at 17:33