Skip to content

Instantly share code, notes, and snippets.

@l1905
Created January 22, 2019 06:44
Show Gist options
  • Save l1905/883dbe1b9385ff1ac33a0507b0a8d23c to your computer and use it in GitHub Desktop.
Save l1905/883dbe1b9385ff1ac33a0507b0a8d23c to your computer and use it in GitHub Desktop.
php-object2classobject
#A端使用
#定义类对象
class MyObject_01
{
/** @var string */
public $property0;
public function setProperty0($data = "")
{
$this->property0 = $data;
}
public function getProperty0()
{
return $this->property0;
}
}
class MyObject extends MyObject_01
{
/** @var string */
public $property1;
/** @var string */
public $property2;
/** @var string */
public $property3;
/** @var array */
public $array1;
public function getData()
{
return $this->array1;
}
}
#创建类对象
$newMyObject = new MyObject();
#数据赋值
$newMyObject->array1 = "123456";
#格式化为 json字符串
$jsonMy = json_encode($newMyObject);
#B端调用
#序列化解析
$decodeMy = json_decode($jsonMy);
#对象反序列化为【类对象】
function objectToObject($instance, $className) {
return unserialize(sprintf(
'O:%d:"%s"%s',
strlen($className),
$className,
strstr(strstr(serialize($instance), '"'), ':')
));
}
#生成类对象
$newClass = objectToObject($decodeMy, "MyObject");
#组件化获取数据
$newClass->getData();
echo $newClass->setProperty0();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment