开发者

Converting an object to a set of variables

How would you go about converting:

$Object->one;
$Object->two;
开发者_如何转开发

to:

$one;
$two;


Cast it into an array then extract() it.

Keep alcuadrado's comment in mind regarding encapsulation; it's emphasized by the fact that extract() will only work on public instance variables (I've updated my example code to show this).

class TestClass
{
    public $one = 1;
    public $two = 2;
    private $three = 3;
}

$object = new TestClass;
extract((array) $object);

var_dump($one, $two, $three);

Output:

Notice: Undefined variable: third in...
int(1)
int(2)
NULL


If you use a foreach loop on an object, it will iterate over the visible properties without exposing private members.

foreach ($object as $key => $value){
  $$key = $value;
}


Try: extract(get_object_vars($Object));

That will only get the public variables. If you want private, then you'd need to call it from within the object itself.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜