如何将变量传递到 PHP 类中包含的文件?

发布于 2024-07-14 13:40:05 字数 431 浏览 6 评论 0原文

因此,我正在开发自己的小型 MVC 框架作为学习练习。 它工作得很好,但我希望能够在没有 $this 的情况下引用视图文件中的变量。

例如,我有一个实例化视图对象的控制器对象。 我从控制器将变量传递到视图,如下所示

$this->view->foo = "bar";

然后视图对象包含视图的相关代码(例如:myView.phtml)。 因此,要在视图文件中访问“foo”,我使用这个

echo $this->foo;

但是我想做的是,我不知道这是否可能,或者我是否遗漏了一些明显的东西,但我想做的是引用像这样的变量

echo $foo;

如果我不发布整个源代码,任何人都可以指出我正确的方向吗?

So I'm working on my own little MVC framework as a learning exercise. It's working great, but I want to be able to reference variables in my view files without $this.

So for example I have a controller object which instantiates a view object. From the controller I pass the variables to the view like this

$this->view->foo = "bar";

Then the view object includes the relevant code for the view (eg: myView.phtml). So to access "foo" in the view file I use this

echo $this->foo;

But what I would like to do, and I don't know if this is possible or wether I'm missing something obvious, but what I would like to do is reference the variables like this

echo $foo;

Without me posting the entire source, can anyone point me in the right direction?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

ま昔日黯然 2024-07-21 13:40:05

如果您希望视图对象中的每个变量在视图中可用,您可以将变量添加到视图对象的数组属性中,然后使用 extract() 使它们可用:

$this->view->variables['foo'] = 'bar';

extract($this->view->variables); // now $foo = 'bar';

我不是 extract() 的忠实粉丝,但这将实现您正在寻找的东西。

If you would like every variable in the view object to be availble inside the view, you could add your variables to a property of the view object that is an array and then use extract() to make them available:

$this->view->variables['foo'] = 'bar';

extract($this->view->variables); // now $foo = 'bar';

I'm not a big fan of extract(), but this would accomplish what you are looking for.

書生途 2024-07-21 13:40:05

您可以编写一些代码来解析您的 html 视图输入并自动将您的条目从 $foo 或 [foo] 修改为 $this->foo。

因此,您可以在 html 视图中放置类似的内容:

<p>[foo]</p>

然后让一些视图代码解析该文件并将 [foo] 的所有实例更改为 $this->foo 的值。 所以你的输出变成:

<p>I'm the foo value</p>

或者,你可以使用类似 Smarty 的东西 - 它为你做这个并且有许多其他功能也有使用它的理由。

You could write some code that parses your html view input and automatically modifies your entries from $foo or [foo] to $this->foo.

So you could put something like this in your html view:

<p>[foo]</p>

and then have some view code parse the file and change all instances of [foo] to the value of $this->foo. So your output becomes:

<p>I'm the foo value</p>

Or, you could use something like Smarty - it does this for you and has many other reasons to use it too.

人生戏 2024-07-21 13:40:05

您是否尝试过提取? 您必须添加一个方法将所有变量放入数组中。 唯一真正的限制是这使得变量只读。

Have you tried extract? You'll have to add a method to put all your variables into an array. The only real limitation is this makes the variables read only.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文