downloads | documentation | faq | getting help | mailing lists | reporting bugs | sites | links | my 
search for in the  
view the version of this page
Last updated: Thu, 21 Aug 2003


Object Initialization

To initialize an object, you use the new statement to instantiate the object to a variable.

class foo
    function do_foo()
        echo "Doing foo."; 

$bar = new foo;

For a full discussion, please read the section Classes and Objects.

Converting to object

If an object is converted to an object, it is not modified. If a value of any other type is converted to an object, a new instance of the stdClass built in class is created. If the value was null, the new instance will be empty. For any other value, a member variable named scalar will contain the value.

$obj = (object) 'ciao';
echo $obj->scalar;  // outputs 'ciao'

add a note add a note User Contributed Notes
info at keltoi-web dot com
26-Aug-2003 04:26
PHP supports recursive type definitions as far as I've tried. The class below (a _very_ simple tree) is an example:

class Tree {

var $_value = null;
var $_children = array();

function Tree ($value) {
  $this->_value = $value;

function addChild ($value) {
  $aux_node = new Tree ($value);
  $this->_children [] = $aux_node;
  return $aux_node;

As you can see, in addChild we reference Tree again...

However, you must be careful about references. See the chapter "References explained" for more details.

Hope this helps.
php at electricsurfer dot com
22-May-2003 11:25
Here's an example on operator precedence between ->  and []
& what happens with $object->$member[$array_element]

class c
$a = array('a'=>'aa','b'=>'ab');
$b 'c';
$this->a['a']; // -> 1st
echo $this->a['b']; // outputs 'ab'
$a 'a';
$b 'b';
$this->$a[$a]; // [] 1st, not what I expected
echo $this->$a[$b]; // does NOT output 'ab'
$this_a =& $this->$a// work-around
echo $this_a[$a]; // no question
echo $this_a[$b];
$a_arr = array('a'=>'b');
$this->$a_arr[$a]; // [] 1st => outputs 'c'
$c = new c();
adolfoabegg at _plzdontspam_hotmail dot com
29-Nov-2002 04:26
[Editor's note: PHP already does this for you when registering an object in a session, see the third paragraph from the bottom in the page "Serializing objects - objects in sessions"]

If you want to use an object with php sessions, you can convert it into a string and then save this string into a session var

Try this:

----- obj.php
class ShoppingCart{
 var $result;
 function SayHi(){
   $result = "Hi there!";
   return $result;

----- save_obj.php -----
require ('obj.php');
$Cart = new ShoppingCart;

$ses_obj = serialize ($Cart);

--------- get_obj.php ----

$Cart = unserialize ($HTTP_SESSION_VAR['ses_obj']);

$aux = $Cart->SayHi();

print $aux; //prints Hi there!

 Last updated: Thu, 21 Aug 2003
show source | credits | sitemap | mirror sites 
Copyright © 2001-2003 The PHP Group
All rights reserved.
This mirror generously provided by:
Last updated: Sat 01 Nov 2003 04:13:36 EST EST