开发者

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

开发者 https://www.devze.com 2023-03-21 13:34 出处:网络
I have this simple issue. In this simple script: <?php class MyClass { public var1 = \'1\'; public var2 = \'\';

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

精彩评论

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