Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

oop

php

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.

like image 881
AeroCross Avatar asked Jul 20 '11 16:07

AeroCross


1 Answers

Try this:

foreach ($class as $key => $value) {
    if (empty($value)) {
        $value = 'something';
        $class->$key = $value;
    }
}
like image 187
linepogl Avatar answered Nov 05 '22 05:11

linepogl