开发者

Looping through PHP object members and assign a value to members

I know I can loop through a PHP object and obtain the values of it's members like so:

class MyObject {

    public $one = 1;
    public $two = 2;
    public $three = 3;

    function getMemberValues() {
        foreach($this as $memb => $value) {
            echo $value." ";
        }
    }
}
$o = new MyObject();
$o->getMemberValues();
// prints 1 2 3

but what I want to be able to do is loop开发者_JAVA百科 through the members and assign a value to each one.

I can't figure out the syntax for it though.

$this[$memb] = 111;

doesn't work because you get a

Cannot use object of type MyObject as array 

error, and

$this->$memb

obviously isn't valid either.

Is this possible?

Many thanks


Yes, $this->$memb is valid.

You can assign to a property like this:

$memb = 'one';
$this->$memb = 1;

This also works for functions, and this is documented here


and

$this->$memb

obviously isn't valid either.

Have you tried it? It looks perfectly valid to me.

foreach ($this as $memb => $val) {
    $this->$memb = 'toto';
}

The code above should work perfectly.


Maybe

function getMemberValues() {
    foreach($this as &$value) {
        $value = $newval;
    }
}


http://php.net/manual/en/function.get-object-vars.php

function getMemberValues() 
{
  echo implode(' ', get_object_vars($this));
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜