1

I've got a web application that I'm building on the FuelPHP framework. My local development environment is running PHP 5.4 while my server is running PHP 5.3. In my development environment, from my main template file, I'm able to

<?php var_dump($this->active_request); ?>

This results in a bunch of data about the request (a Fuel\Core\Request object) being dumped into a modal dialog box for me to reference. However, when I try to run the exact same script on the production server (PHP 5.3), it gives me the old "ErrorException [ Error ]: Using $this when not in object context"

I'm aware of the difference between using instantiated objects and statically accessed methods. My question is, why would the different versions of PHP treat the same template file as having a different context? Or is there some other configuration nuance that would result in the apparently divergent functionality of the two environments?

Ben Harold
  • 6,242
  • 6
  • 47
  • 71

2 Answers2

2

I don't know FuelPHP but it looks like the templates are included inside of a closure. Since PHP 5.4 closures can be bound to an object and have $this. Per default it is the object where the closure was created. See also: https://stackoverflow.com/a/5734109/664108

Community
  • 1
  • 1
Fabian Schmengler
  • 24,155
  • 9
  • 79
  • 111
1

Correct. Views are rendered in a closure which is designed to act like a sandbox.

$this in a view should not work, but it looks like in PHP 5.4 it will pick up an object higher in the callstack, as it gives you Request, and not View or your controller. Which already indicates it's not reliable to use, as what $this represents will depend on the callstack.

Even if you don't use a templating engine, it is considered bad practice to use "logic" in your views, other than the logic needed to generate the HTML. Pass the data required to the view, either from the controller, or use a Viewmodel to prep the data.

WanWizard
  • 2,574
  • 15
  • 13
  • More info on closure binding in PHP 5.4: http://christophh.net/2011/10/26/closure-object-binding-in-php-54/ – Ben Harold Jun 28 '13 at 19:41