简体   繁体   English

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

[英]How can I pass variables to a file included in a class in PHP?

So I'm working on my own little MVC framework as a learning exercise. 因此,我正在研究自己的小MVC框架作为学习练习。 It's working great, but I want to be able to reference variables in my view files without $this. 它工作得很好,但是我希望能够在没有$ 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). 然后,视图对象包括该视图的相关代码(例如:myView.phtml)。 So to access "foo" in the view file I use this 所以要在视图文件中访问“ foo”

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? 没有我发布整个源代码,没有人能指出我正确的方向吗?

You could write some code that parses your html view input and automatically modifies your entries from $foo or [foo] to $this->foo. 您可以编写一些代码来解析您的html视图输入,并自动将您的条目从$ foo或[foo]修改为$ this-> foo。

So you could put something like this in your html view: 因此,您可以在html视图中放置以下内容:

<p>[foo]</p>

and then have some view code parse the file and change all instances of [foo] to the value of $this->foo. 然后让一些视图代码解析该文件,并将[foo]的所有实例更改为$ 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. 或者,您可以使用Smarty之类的东西-它可以为您做到这一点,并且还有很多其他原因也要使用它。

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. 唯一真正的限制是,这会使变量变为只读。

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: 如果希望视图对象中的每个变量在视图内可用,则可以将变量添加到作为数组的视图对象的属性中,然后使用extract()使它们可用:

$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. 我不是extract()的忠实拥护者,但这可以满足您的需求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM