假设我们有一个PHP类发票和项目:JSON到定制的PHP对象实例
class Item{
public $CID;
public $CATID; // category id...
public $net;
public $t1;
public $t2;
public $total;
}
class invoice{
public $items = array(); //array of object item;
public $date;
public $title;
public $description;
public $subtotal;
public $t1;
public $t2;
public $total;
public function __construct(){
}
}
对象发票包含几种方法,如:添加项目,remove_item,重新计算,一套税收和东西......这是有点复杂。 我想出如何使用该对象的实例解析成JavaScript:
$json=json_encode((array)$invoice);
然后在JavaScript中,我有相同的对象定义,同样的方法,然后我用:
test = jQuery.parseJSON('<?php= $json?>');
test.__proto__ = invoice.prototype;
所以非常好,我的测试变量现在已经成为javascript中的发票对象,并且我可以使用invoice和item javascript类中定义的方法。几个操作后我可以重新发送对象到PHP(让由AJAX说),使用以下:
function send_ajax(){
$.ajax({
url: "ajax.php",
type: "POST",
data: ({
invoice:JSON.stringify(test)
}),
success: function(msg){
$('#response').html(msg);
}
});
}
然后,服务器端我使用json_decode到JSON转换成一个数组。这是我卡住的地方!我无法将我的$ invoice []或stdObjcect投入到我的发票类中。我也在ASP .net C#中编写代码,这样的事情很容易实现。我需要实现这样的事情的原因很简单:我需要使用PHP发票类中的方法解析JSON ...任何人都有想法?
我之前想出的唯一一件事就是手工解析JSON对象...是否有任何其他的“内置”的方式
public function __construct($json = null){
if ($json != null){
$json=json_decode($json, true);
for($i=0;$i<count($json[items]);$i++){
$newItem= new Item();
foreach ($json[items][$i] as $key=>$value){
$newItem->$key=$value;
}
array_push($this->items,$newItem);
}
foreach($json as $key =>$value){
if(!is_array($value)){
$this->$key=$value;
}
}
}
}
你为什么要这么做? PHP!= JS。 – PeeHaa 2013-03-24 18:06:19
@PeeHaa我相信答案在于'我也在ASP.net C#代码中......' – deviousdodo 2013-03-24 18:07:09
原型继承与传统的对象继承模型不同。 – PeeHaa 2013-03-24 18:08:29