将对象附加到php中的另一个对象
我有这个对象:
foreach(range(1,$oc->num_users) as $num) {
$user = 'user' . $num;
$$user = mysql_fetch_object(mysql_query("SELECT user".$num.", user".$num."_ready, FROM oc_db WHERE leader='".$_SESSION['username']."' "));
这给出了名为 user1..X 的对象
,稍后我有一个类似的函数,其中我使用代表连接到数据库的用户名的 $$user->$user
以获得更多信息。
$$user = mysql_fetch_object(mysql_query("SELECT x, y, z FROM user_db WHERE username='".$$user->$user."' "));
这也会生成名为 user1..X 的对象,但我不想替换之前创建的对象,而是想将此值附加到我在第一个函数中创建的对象中。 $$user
是对象的名称。我想在最后一个函数中做类似 $$user .= fetch_object
的事情,但当然事情没那么简单。
I have this object:
foreach(range(1,$oc->num_users) as $num) {
$user = 'user' . $num;
$user = mysql_fetch_object(mysql_query("SELECT user".$num.", user".$num."_ready, FROM oc_db WHERE leader='".$_SESSION['username']."' "));
This gives objects named user1..X
later I have a simular function like this, where I use the $$user->$user
that represent a username to connect to the db to get additional information.
$user = mysql_fetch_object(mysql_query("SELECT x, y, z FROM user_db WHERE username='".$user->$user."' "));
This also makes objects named user1..X, but instead of replacing the object created earlier I want to append this values to the object I created in the first function. $$user
is the name of the objects. I would like to do something like $$user .= fetch_object
in the last function, but off course it's not that simple.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为了将一个对象附加到另一个对象,您只需迭代第一个对象,然后将找到的每个属性分配给第二个对象:
In order to append one object to another you simply need to iterate through the first object and then assign each property you find to the second one:
顺便说一句,如果您尝试访问对象的
user
属性,那么您应该使用$$user->user
,如$ $user->$user
将尝试访问编号属性(例如,对于对象$user12
,您正在尝试访问$user12->user12
代码>)。我还会考虑使用数组,正如 fredley 建议的那样(即使用$user[$num]
而不是$user = 'user'.$num
)。要解决您最初的问题,您可以尝试向
user
类添加一个方法,例如append.=
连接赋值运算符>,然后使用它将获取的对象附加到当前对象,例如$user->append( fetch_object(...));
。在append
方法中,您可以定义自己的规则,了解如何将获取的对象添加到当前用户对象。As a couple of asides, if you are trying to access the
user
property of the object, then you should use$$user->user
, as$$user->$user
will be trying to access a numbered property (e.g. for object$user12
, you're trying to access$user12->user12
). I would also consider using an array, as fredley suggested (i.e. use$user[$num]
instead of$user = 'user'.$num
).To approach your original question, instead of using the
.=
concatenation assignment operator, you could try adding a method to youruser
class, such asappend
, then using it to append the fetched object to your current object like$user->append( fetch_object(...));
. In theappend
method, you can define your own rules for how a fetched object is added to your current user object.