如何将变量传递到 PHP 类中包含的文件?
因此,我正在开发自己的小型 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您希望视图对象中的每个变量在视图中可用,您可以将变量添加到视图对象的数组属性中,然后使用 extract() 使它们可用:
我不是 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:
I'm not a big fan of extract(), but this would accomplish what you are looking for.
您可以编写一些代码来解析您的 html 视图输入并自动将您的条目从 $foo 或 [foo] 修改为 $this->foo。
因此,您可以在 html 视图中放置类似的内容:
然后让一些视图代码解析该文件并将 [foo] 的所有实例更改为 $this->foo 的值。 所以你的输出变成:
或者,你可以使用类似 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:
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:
Or, you could use something like Smarty - it does this for you and has many other reasons to use it too.
您是否尝试过提取? 您必须添加一个方法将所有变量放入数组中。 唯一真正的限制是这使得变量只读。
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.