Possible to access $this from include()'d file

2019-03-03 09:34发布

问题:

I'm working on a WordPress Widget and the examples all have huge HTML/PHP chunks intermixed and it is impossible to read, so in the interest of trying to clean stuff up I'd like to move all of the HTML rendering to a separate PHP file that will be include()'d.

The trick to this is, the file I include doesn't appear to have access to $this and I'm unsure how to fix that.

widget.php

class Preorder extends WP_Widget {
    ...
    function form() {
        include('form.php');
    }
}

form.php

<p>
   <?php echo $this->get_field_id('title'); ?>
</p>

Which results in [31-Aug-2011 19:59:19] PHP Fatal error: Call to a member function get_field_id() on a non-object in ... so clearly $this doesn't come along for free. I've tried aliasing $this to another variable & even just for fun using the global keyword without success.

Hopefully I missed something easy.

回答1:

Forgot that I was iterating over the directory & include-ing every .php file, renamed form.php to form.tmpl and appears to work.

Durr.