开发者

Iterate through an object's properties and modify the original object

I have this simple issue. In this simple script:

<?php 

class MyClass {
    public var1 = '1';
    public var2 = '';
    public var3 = '3';
}

$class = new MyClass;

foreach ($class as $key => $value) {
    echo $key . ' => ' . $va开发者_如何学Clue . '<br />';
}

?>

The result would be:

var1 => 1

var2 =>

var3 => 3

If I want to iterate through all those properties so I can find out which one is empty, how can I assign a value to that empty property in the object?

foreach ($class as $key => $value) {
    if (empty($value)) {
        $value = 'something';
    }
}

... is not working because I guess that PHP thinks that $value is an actual variable, not a reference.


Try this:

foreach ($class as $key => $value) {
    if (empty($value)) {
        $value = 'something';
        $class->$key = $value;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜