AeroCross
AeroCross

Reputation: 4319

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 . ' => ' . $value . '<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.

Upvotes: 6

Views: 5441

Answers (1)

linepogl
linepogl

Reputation: 9335

Try this:

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

Upvotes: 18

Related Questions