0

I'm learning PHP OOP, and getting used to all of these objects. I can't find the answer of a little question (maybe it's obvious, but I m new to objects...) :

When I create an object in a PHP file called via an $.ajax function, I want to deliver the answer back. But how am I supposed to send back the object to my ajax call ? Before OOP, I was putting everything into an array, then json_encode() the array, and everything worked perfectly. How to adapt this using OOP ?

Thanks a lot for your answers Romain

Example :

On the client side

$.ajax(
{
  url:"test.php",
  type:"POST",
  dataType:"json",
  success(function(json))
  {
    // json into template
  }
});

On the server side : test.php

require_once("bdd.php");

function loadClass($class)
{
require $class.".class.php";
}

spl_autoload_register('loadClass');

$PersonneM = new PersonneManager($db);

$perso = $PersonneM->get("123456");

$perso = serialize($perso); // ????????????

header('Content-type: application/json');
echo json_encode(array("result",$perso));
lahud
  • 37
  • 4

2 Answers2

0

@lahud: Generally we use XML and JSON formats to send data from server side to client side. PHP Objects are used only at its server end (at php level). You can result to client in a standard data format like xml and json.

If you want to store php object, you can use serialize function to store object as string. Hope its clear to you.

Pankaj Garg
  • 1,272
  • 15
  • 21
0

@Pankaj

Yes of course I often send JSON results to my client and write it down with a template like Mustache. But what is the correct way to convert the $object into JSON ?

Maybe :

$array = (array)$object;
header('Content-type: application/json');
echo json_encode(array("response" => $array));
lahud
  • 37
  • 4