PHP 将所有对象属性复制到此
我在 PHP 中有一个 MyObject
类型的对象。
$myObject instanceof MyObject
现在,在class MyObject
中,有一个非静态函数,在那里,我使用了对“me”的引用,就像$this
一样,但我也有那里有另一个物体。
是否可以在不执行 $this = $myObject
的情况下实现或多或少相同的效果,例如 set_object_vars($this, get_object_vars($myObject))
?
I have an object in PHP, of the type MyObject
.
$myObject instanceof MyObject
Now, in the class MyObject
, there is a non-static function, and in there, I use the reference to "me", like $this
, but I also have another object there.
Is it possible, without doing $this = $myObject
, to achieve more or less the same effect, like something of the sort set_object_vars($this, get_object_vars($myObject))
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我猜会做你想做的事,但你应该注意以下几点:
get_object_vars
只会找到非静态属性get_object_vars
只会找到可访问的属性根据范围根据范围部分非常重要,可能值得更多解释。您是否知道 PHP 中的属性范围是类相关而不是实例相关?
这意味着在上面的示例中,如果您在
MyObject
中有一个private $bar
属性,get_object_vars
会看到它,因为您处于MyObject
类的实例。如果您尝试导入另一个类的实例,这显然不起作用。Will do what you want I guess, but you should be aware of the following:
get_object_vars
will only find non-static propertiesget_object_vars
will only find accessible properties according to scopeThe according to scope part is quite important and may deserve a little more explanation. Did you know that properties scope are class dependent rather than instance dependent in PHP?
It means that in the example above, if you had a
private $bar
property inMyObject
,get_object_vars
would see it, since you are in an instance of aMyObject
class. This will obviously not work if you're trying to import instances of another class.@Geoffrey Bachelet,我们可以改进这一点:
不同之处在于,您可以传递普通数组(哈希表)以及对象。想象一下来自数据库的一些数据的例子。
@Geoffrey Bachelet we can improve this:
The difference is here that you can pass an ordinary array (hashtable) as well as an object. Think in example about some data coming from the database.