JSON返回的自定义

时间:2023-03-09 19:13:05
JSON返回的自定义

当返回json格式的数据时,不想自己组织结果集,可以利用类的call方法。

json类:

 <?php
class Json { private $_data; public function __construct() {
$this->_data = array();
} public function __call($method, $args) {
if (!isset($args[0])) return null; $this->_data[$method] = $args[0]; return $this;
} function __set($prop_name, $prop_value) {
$this->_data[$prop_name] = $prop_value;
return true;
} function __get($prop_name) {
return $this->_data[$prop_name];
} public function __toString() {
return json_encode($this->_data);
} public function out() {
echo $this->__toString();
} }

调用json类:

 <?php
require 'json.php'; class Test_Json {
public $json; public function __construct() {
$this->json = new Json(); echo $this->json->code(1)->alert('tttt')->gg(array('ss')); exit;
}
} $test_json = new Test_Json();