一千萬個為什麽

搜索

PHP:如何為局部函數變量實現類似__get的方法

我對__get()並不陌生,過去曾用它來制作一些非常方便的庫。但是,我遇到了一個新的挑戰(PHP 5.3,這個問題的縮寫和簡化我的代碼):

<?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 ??";
    }
}

?>

上面是一個非常非常簡化的加載View的系統。此代碼將調用視圖並顯示它:

<?php

require_once("View.php");

use test\View;

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

?>

我對此代碼的目標是允許視圖“myview.php”包含如下代碼:


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

並且,與上面的代碼一起使用,這將輸出“Hello Tom!你的電子郵件是??電子郵件??”

但是,這不起作用。視圖包含在類方法中,因此當它引用$ user和$ email時,它會查找本地函數變量 - 而不是屬於View類的變量。因此,__get永遠不會被觸發。

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.

思考?有沒有幹凈的方法來做到這一點,還是我被迫采用hacky解決方案?

最佳答案

EDITING MY ANSWER. Abit of a "hack around" but a potential solution. May want to "reset" the error_handler to more generic functionality.

view.php

<?php
error_reporting(E_ALL);
ini_set("display_errors", 0);
class View {
    function display($file, $values) {        
        set_error_handler(array($this, '__get'), E_NOTICE);        
        extract($values);
        include($file);
    }

    function __get($vaule)
    {
        echo 'Unknown';
    }
}

$View = new View;
$values = array('user' => 'Tom',
               'email' => '[email protected]');

$View->display('/filename.php', $values);
?>

filename.php

Hello <?php echo $user; ?>, your email is <?php echo $email; ?> and your are <?php echo $age; ?> years old.

產量

Hello Tom, your email is [email protected] and your are Unknown years old.

轉載註明原文: PHP:如何為局部函數變量實現類似__get的方法