Learning Points
- Object Object turn
- String objects turn
- Object array transfer
- NULL turn objects
<?php
class human{
var $height=0;
function setHeight()
{
$this->height=173;
}
}
$oldman=new human();
var_dump($oldman);// object(human)[1] public 'height' => int 0
echo '<hr />';
//对象转对象
$newman=(object)$oldman;
var_dump($newman);// object(human)[1] public 'height' => int 0
echo '<hr />';
//字符串转对象
$newstring=(object)"Hello World!";
var_dump($newstring); //object(stdClass)[2] public 'scalar' => string 'Hello World!' (length=14)
echo '<hr />';
//数组转对象
$numArr=array(1,2,3);
$newNum=(object)$numArr;
var_dump($newNum);
echo '<hr />';
//echo $newNum->0;//有点奇怪如何进行访问呢?
/*
*
* object(stdClass)[3]
public 0 => int 1
public 1 => int 2
public 2 => int 3
*/
echo "<br />";
//NULL 转对象
$null=(object)NULL;
var_dump($null);
?>
Learning Points
- objectToArray
- arrayToObject
- is_object: to determine whether the object is
- get_object_vars: obtaining object variable
- __construct: Using Constructors
- array_map: temporarily unknown
<?php
/**
* 对象和数组的相互转化
* @link http://www.phpddt.com PHP分享平台
*/
class Test{
public $a;
public $b;
//定义构造函数
public function __construct($a) {
$this->a = $a;
}
}
//对象转数组,使用get_object_vars返回对象属性组成的数组
function objectToArray($obj){
//如果参数是对象就获取对象的变量
$arr = is_object($obj) ? get_object_vars($obj) : $obj;
if(is_array($arr)){
return array_map(__FUNCTION__, $arr);
}else{
return $arr;
}
}
//数组转对象
function arrayToObject($arr){
if(is_array($arr)){
return (object) array_map(__FUNCTION__, $arr);
}else{
return $arr;
}
}
$test = new Test('test1');
$test->b = new Test('test2');
print_r($test);
echo '<hr />';
//将一个对象转换成一个数组
$array = objectToArray($test);
print_r($array);
echo '<hr />';
$object = arrayToObject($array);
print_r($object);
?>