通过类访问变量 [英] Accessing variables through classes
问题描述
所以可以说我有一个实例化 Page
对象的核心程序类。
So lets say I have a core program class which instantiates a Page
object.
此 Page
对象具有属性 $ id
(这是我们当前所在页面的页面ID)。
This Page
object has a property $id
(which is the page id of the page we're currently on).
在 Page
类中,它在数据库中查找,并通过实例化 Template
对象。
In the Page
class it looks in the database and it sets up the template for the page by instantiating a Template
object.
在此 Template
对象中,我想放置一个内容块。这由 Content
类处理,我在 Template
类中对此类进行了说明。
In this Template
object I want to put in a content block. This is handled by a Content
class which I isntantiate in the Template
class.
现在要使此内容正常工作,我需要能够从页面$ c $获取
$ id
c>程序核心拥有的对象。有什么办法吗?遍历页面id似乎很不愉快,尤其是当到达页面id时,类之间可能有10层?
Now for this content to work properly I need to be able to get the $id
from the Page
object owned by the program core. Is there any way to do this? It seems rather fiddly to pass through the page id, especially as when it gets to it there could be 10s of layers between classes?
如果我将$ id变量设为静态(静态$ id;
)然后可以使用 Page :: $ id
再次获取它,而不必访问我在其中设置对象的实际实例?
If I make the $id variable static (static $id;
) then can I get it again using Page::$id
instead of having to access the actual instance of the object that I set it in?
谢谢
Tom
推荐答案
您追求的目标通常由 依赖注入。在Template构造函数中创建 Template
对象时,通常会传入 Page
这样的对象。 Page对象本身可以是Template的属性,也可以只是$ id属性。因此不必在每次函数调用时都传递id。
What you're after is often handled by "dependency injection". It's quite common to pass in an object like your Page
object at creation of the Template
object, in the Template constructor. The Page object itself may be a property of Template, or only its $id property. So it isn't necessary to pass in the id on every function call.
Template :: __ construct($ Page)
如果Template类与Page类相关,则它也可以扩展Page类,从而可以访问 Page :: $ id
(如果该财产受到保护 c)或
公共
。
If the Template class is related the Page class, it may also extend the Page class, whereby it would already have access to the Page::$id
if that property was protected
or public
.
这篇关于通过类访问变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!