将php数组转换为对象$ this

时间:2016-04-12 14:02:47

标签: php arrays object this

我的键和值如下:

[store_id] => 1
[store_name] => StarShop
[store_phone] => 62-22-8383838
[store_email] => admin@starshop.com

我用它从上面的数组中用$ this创建对象

foreach($above_array as $key => $value){
  $this->$key = $value;
}

echo $this->store_name; // this does not work, please help

1 个答案:

答案 0 :(得分:0)

如果您不在课堂内,则无法使用$this->

<?php

$a = array(
'store_id' => 1,
'store_name' => 'StarShop',
'store_phone' => '62-22-8383838',
'store_email] => admin@starshop.com',
);

$obj = new StdClass;               // create new object
foreach($a as $key => $value){     // iterate as before
  $obj->$key = $value;             // add properties to object
}

echo $obj->store_name; 

?>

Demo