|
if(!function_exists("copy_properties"))
{
function copy_properties($fromObj,$toObj)
{
foreach($fromObj as $key=>$value)
{
if(is_array($toObj))
{
$toObj[$key] = $value;
}
else if(is_object($toObj))
{
if(property_exists($toObj,$key))
{
$toObj->$key = $value;
}
}
}
return $toObj;
}
}
demo如下:
<?php
if(!function_exists("copy_properties"))
{
function copy_properties($fromObj,$toObj)
{
foreach($fromObj as $key=>$value)
{
if(is_array($toObj))
{
$toObj[$key] = $value;
}
else if(is_object($toObj))
{
if(property_exists($toObj,$key))
{
$toObj->$key = $value;
}
}
}
return $toObj;
}
}
function pre_dump($obj)
{
echo "<pre>";
var_dump($obj);
echo "</pre>";
}
class TestVo
{
public $id;
public $name;
public $age;
}
function test()
{
$test_array = array(
"id" => 1,
"name"=> "ongsh",
"age"=> 25
);
//数组到对象
$vo = copy_properties($test_array,new TestVo());
pre_dump($vo);
//对象到对象
$newVo = copy_properties($vo,new TestVo());
pre_dump($newVo);
//数组到对象
$arr = copy_properties($newVo,array());
pre_dump($arr);
//数组到数组
$newArr = copy_properties($arr,array());
pre_dump($newArr);
}
//execute
test();
?>
页面输出:
object(TestVo)#1 (3) {
["id"]=>
int(1)
["name"]=>
string(5) "ongsh"
["age"]=>
int(25)
}
object(TestVo)#2 (3) {
["id"]=>
int(1)
["name"]=>
string(5) "ongsh"
["age"]=>
int(25)
}
array(3) {
["id"]=>
int(1)
["name"]=>
string(5) "ongsh"
["age"]=>
int(25)
}
array(3) {
["id"]=>
int(1)
["name"]=>
string(5) "ongsh"
["age"]=>
int(25)
} |
|
|