[techtalk] Re: storing objects in a db with PHP

eito eito at cs.pdx.edu
Mon Jun 19 15:56:39 EST 2000


On Mon, Jun 19, 2000 at 03:57:28PM -0400, Erb, Maria wrote:
> does anyone know how to store objects in a database using PHP?  I've created
> a class which has two attributes which are arrays.  I need to store the
> whole object in a db but I'm not sure how to do it.  When I try to serialize
> the array, the info is stored in a MySQL table, but I can't seem to retrieve
> the info (with unserialize) and then use the info as an object.  Thanks for
> any help!!!  And how about storing an array of objects in a db?

Hi,

I think that the following example shows how to serialize and
unserialize object, and to show attributes of object.

The serialize function in PHP cannot serialize object's methods.
But, you can cast unserialized object as array. Then, you can
access attribute. If you display serialized object and array,
you see why and how to access attributes.


Hope this helps,

:eito


<?php
  class Egg {
    var $content = array("yellow"=>1, "white"=>2);
  }
  class Spam {
    function get_egg($key) { return $this->egg[$key]; }
    var $egg = array("egg"=>new Egg);
  }

  // create a new object of Spam, and store a new object of Egg
  $s = new Spam;
  $egg = $s->set_egg(new Egg);

  // cast a Egg object as array, and access its attribute
  $egg = (array)$s->get_egg();
  echo($egg["content"]["yellow"]); echo("<br>\n");

  // serialize Spam object, and show its content
  $p = serialize($s);
  echo("$p<br>\n");

  // unserialize, and check if it is an object
  $a = unserialize($p);
  echo(gettype($a)); echo("<br>\n");

  // cast the unserialized object as array,
  // then serialize the array, and show content
  $m = (array)$a;
  echo(serialize($m)); echo("<br>\n");

  // get Egg object from the array, and show the type
  // then, cast the Egg object as array, and access attribute
  $e = $m["egg"];
  echo(gettype($e)); echo("<br>\n");
  $g = (array)$e;
  echo(gettype($g)); echo("<br>\n");
  $h = $g["content"]["yellow"];
  echo("$h<br>\n");
?>






More information about the Techtalk mailing list