PHP: How to implement a __get-like method for local function variables

Posted by Tom Frost on Stack Overflow See other posts from Stack Overflow or by Tom Frost
Published on 2010-04-19T16:44:22Z Indexed on 2010/04/19 16:53 UTC
Read the original article Hit count: 332

Filed under:
|
|

I'm no stranger to __get(), and have used it to make some very convenient libraries in the past. However, I'm faced with a new challenge (PHP 5.3, abbreviated and simplified my code for this question):

<?php
namespace test;

class View {
    function __construct($filename, $varArray) {
        $this->filename = $filename;
        $this->varArray = $varArray;
    }

    function display() {
        include($this->filename);
    }

    function __get($varName) {
        if (isset($this->varArray[$varName]))
            return $this->varArray[$varName];
        return "?? $varname ??";
    }
}

?>

Above is a very, very simplified system for loading a View. This code would call the view and display it:

<?php

require_once("View.php");

use test\View;

$view = new View("views/myview.php", array("user" => "Tom"));
$view->display();

?>

My goal for this code is to allow the view "myview.php" to contain code like this:

<p>
    Hello <?php echo $user; ?>!  Your E-mail is <?php echo $email; ?>
</p>

And, used with the above code, this would output "Hello Tom! Your E-mail is ?? email ??"

However, this won't work. The view is being included within a class method, so when it refers to $user and $email, it's looking for local function variables -- not variables belonging to the View class. For this reason, __get never gets triggered.

I could change all my view's variables to things like $this->user and $this->email, but that would be a messy and unintuitive solution. I'd love to find a way where I can reference variables directly WITHOUT having PHP throw an error when an undefined variable is used.

Thoughts? Is there a clean way to do this, or am I forced to resort to hacky solutions?

© Stack Overflow or respective owner

Related posts about php

Related posts about php5