Possible to access $this from include()'d file in PHP class?

£可爱£侵袭症+ 提交于 2019-12-02 06:54:04

问题


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.



来源:https://stackoverflow.com/questions/7262705/possible-to-access-this-from-included-file-in-php-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!