PHP 类属性/方法同步

发布于 2024-12-19 15:36:23 字数 712 浏览 0 评论 0原文

修订 - 我有多个类定义分布在文件中(每个文件一个类)。我想做的是这个;我有一个名为 Master 的类,我为其创建了一个实例,而 Master 对象又创建了我定义的其余类的实例。 Master 在其中定义了我的所有属性。

Master 创建的实例中,我希望能够直接从 $this 使用 Master 的属性/方法,即 $ this->methodInMaster,无需将 Master 的对象传递给新实例、存储它并调用 $this->MasterInstance->methodinMaster< /代码>。有什么办法可以实现这一点吗?

extends 关键字在这里根本没有帮助我; Master 创建实例的类将继承 Master 的属性和方法,但这些实例对 Master 的属性所做的任何更改都不会“已保存”在Master 对象中,只是进行更改的对象。换句话说,这些更改在任何其他类中都不可见。

我相信这是不使事物静态化的限制,因此没有“实例”,但是有没有办法使用 call、setget 魔法方法?

Revised - I have multiple class definitions spread across files (one class per file). What I'm trying to do is this; I have a class called Master which I create an instance of, and in turn the Master object creates instances of the rest of my defined classes. Master has all of my properties defined inside it.

In the instances that Master creates, I want to be able to use Master's properties/methods straight from $this i.e $this->methodInMaster, without the need for passing Master's object to the new instance, storing it, and calling $this->MasterInstance->methodinMaster. Is there any way to achieve this?

The extends keyword does not help me here at all; the classes that Master creates instances of will inherit the properties and methods of Master, but any changes these instances make to the properties of Master are not 'saved' in the Master object, just the object that made the changes. In other words, the changes aren't visible in any other class.

I believe this is a limitation of not making things static so that there are no 'instances', but is there a way to get around all this using the call, set and get magic methods?

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

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

发布评论

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

评论(1

沫离伤花 2024-12-26 15:36:23

扩展对您没有帮助,因为它不是您所需要的:如果您想要一个可由多个实例访问的单个对象,您需要一个 单例(它必须是静态的,因为替代方案是采用某种不切实际的形式来共享单个引用)。对于您想要的结构,您将需要一个与 Master 类不同的 Singleton,但可以通过 Master 类访问它。基本上,您的工作流程将是:

  • 在单例中实现您的功能 在
  • Master 的方法中访问单例
  • 像往常一样扩展 Master

这样子类中的每个调用都将透明地“重定向”到对单例的调用。这样做不是很优雅(与直接访问子类中的单例相反),但它应该适合您的设计。

Extends doesn't help you because it's not what you need: if you want a single object that is accessible by many instances, you want a Singleton (it has to be static, because the alternative is having some impractical form of sharing a single reference). For the structure you desire, you will need a Singleton that is different from the Master class, but it's accessed by it. Basically you workflow will be:

  • implement your functionality in the singleton
  • access the singleton in the methods of Master
  • extend Master as usual

This way every call in a subclass will be "redirected" transparently to a call to the singleton. It's not very elegant to do this (as opposed to directly accessing the singleton in the subclasses), but it should work for your design.

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