* getobjectvars.php
<?php
class foo {
private $a = true;
public $b = 1;
public $c = "value of 'c'";
private $d = 10.336;
static $e = ["a", "b", "\n"];
public function test() {
var_dump(get_object_vars($this));
}
public function __toString() {
$a = get_object_vars($this);
$s = "{";
foreach ($a as $name => $value) {
$s .= sprintf("%s:\"%s\",", $name, addslashes($value));
}
// replace last , with }
$s[strlen($s)-1] = "}";
return $s;
}
}
$test = new foo();
// $vars = get_object_vars($test);
echo $test.PHP_EOL;
// $test->test();
* test
php getobjectvars.php
{a:"1",b:"1",c:"value of \'c\'",d:"10.336"}
对于类似数组的结构, 数组封装字段 $_list
public function __toString() {
$s = "[";
foreach ($this->_list as $o) {
$s .= $o->__toString().',';
}
$s[strlen($s)-1] = ']';
return $s;
}
假设当前对象封装的数据在 $_data 字段
public function __toString() {
$s = "{";
foreach ($this->_data as $name => $value) {
if (is_numeric($value)) {
$s .= sprintf("%s:%d,", $name, $value);
} else if (is_bool($value)) {
$s .= sprintf("%s:%s,", $name, $value ? 'true':'false');
} else if(is_string($value)) {
$s .= sprintf("%s:\"%s\",", $name, addslashes($value));
} else {
$s .= sprintf("%s:%s,", $name, \json_encode($value));
}
}
// replace last , with }
$len = strlen($s);
if ($len > 1) {
$s[strlen($s)-1] = "}";
} else {
$s .= "}";
}
return $s;
}