沃梦达 / 编程问答 / php问题 / 正文

可以从 PHP 类中的 include()'d 文件访问 $this 吗?

Possible to access $this from include()#39;d file in PHP class?(可以从 PHP 类中的 include()d 文件访问 $this 吗?)

本文介绍了可以从 PHP 类中的 include()'d 文件访问 $this 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个 WordPress 小部件,这些示例都有巨大的 HTML/PHP 块混合在一起,无法阅读,所以为了尝试清理内容,我想移动所有的 HTML 渲染到一个单独的 PHP 文件,该文件将被 include()'d.

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.

诀窍是,我包含的文件似乎无法访问 $this,我不确定如何解决.

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>

这导致 [31-Aug-2011 19:59:19] PHP Fatal error: Call to a member function get_field_id() on a non-object in ... 很明显 $this 不是免费的.我尝试将 $this 别名为另一个变量 &甚至只是为了好玩而使用 global 关键字没有成功.

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.

推荐答案

忘了我是在遍历目录 &include-ing 每个 .php 文件,将 form.php 重命名为 form.tmpl 并且似乎可以工作.

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

杜尔.

这篇关于可以从 PHP 类中的 include()'d 文件访问 $this 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:可以从 PHP 类中的 include()'d 文件访问 $this 吗?

基础教程推荐