复制 PHP 类的实例,同时保留基类中的数据?
我有以下三个类:
class a
{ public $test; }
class b extends a { }
class c extends a
{
function return_instance_of_b() { }
}
如您所见,类 b
和 c
都派生自 a
。在 c
的 return_instance_of_b()
函数中,我想返回类 b
的实例。基本上 return new b();
,但有一个附加限制:
我需要将基类 (a
) 中的数据复制到 b
的实例中返回的代码>。我该怎么做呢?也许是 clone
关键字的某种变体?
I have the following three classes:
class a
{ public $test; }
class b extends a { }
class c extends a
{
function return_instance_of_b() { }
}
As you can see, both classes b
and c
derive from a
. In the return_instance_of_b()
function in c
, I want to return an instance of the class b
. Basically return new b();
with one additional restriction:
I need the data from the base class (a
) to be copied into the instance of b
that is returned. How would I go about doing that? Perhaps some variant of the clone
keyword?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 get_class_vars 函数检索要复制的变量的名称,然后循环到复制它们。
定义的变量受到保护,因此它们对 get_class_vars 在其范围内可见(因为 c 扩展了 a),但不能在类外部直接访问。您可以将它们更改为 public,但 private 将从 get_class_vars 中隐藏这些变量。
You can use the get_class_vars function to retrieve the names of the variables you want to copy, and just loop to copy them.
The variables that are defined are protected so they are visible to get_class_vars in its scope (since c extends a), but not directly accessible outside the class. You can change them to public, but private will hide those variables from get_class_vars.
我相信你可以通过一些反思来实现这一点。不是很漂亮的代码,我确信有一个更简洁的方法来实现这一点,但在这里你就可以了。
此外,您可以使用 nickb 的答案,但您可以使用
get_parent_class
而不是对类进行硬编码I believe you can achieve this with some reflection. Not very pretty code, I'm sure there is a much more succinct method to achieve this but here you go.
Additionally you could use nickb's answer but instead of hard coding the class you could use
get_parent_class