[英]Dynamically loop through and set PHP class variables
I have a class with several variables like: 我有一类带有几个变量的类:
class ABC
{
$var1=0;
$var2=0;
...
}
Instead of setting variables one by one like; 而不是像一个一个地设置变量;
$ABC=new ABC();
$ABC->var1=1;
$ABC->var2=1;
...
How to loop through all class' (instance) variables and dynamically set them all to some value. 如何遍历所有类(实例)变量并将其全部动态设置为某个值。
You could use get_object_vars to get the non static properties of the object, and then loop through that. 您可以使用get_object_vars获取对象的非静态属性,然后遍历该对象。
$object_vars = get_object_vars($ABC);
foreach ($object_vars as $name => $value) {
$ABC->{$name} = $newVal;
}
See more information here: http://php.net/manual/en/function.get-object-vars.php 在此处查看更多信息: http : //php.net/manual/en/function.get-object-vars.php
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.