[ Team LiB ] Previous Section Next Section

Object Properties

Objects have access to special variables called properties. You can declare them anywhere within the body of your class, but for the sake of clarity, you should define them at the top. A property can be a value, an array, or even another object:


class Item {
  var $name = "item";
}

Notice that we declared our variable with the var keyword. In PHP 4, this was the only way to declare a property. We will look at some additional approaches that PHP 5 makes available later in the hour. If you are writing code that needs to be compatible with PHP 4, then you should use var.

Now any Item object that is created contains a property called $name with the value of "item". You can access this property from outside the object and even change it:


class Item {
   var $name = "item";
}

$obj1 = new Item();
$obj2 = new Item();
$obj1->name = "widget 5442";
print "$obj1->name<br />";
print "$obj2->name<br />";

// prints:
// widget 5442
// item

The -> operator allows you to access or change the properties of an object. Although $obj1 and $obj2 were born with the name of "item", we have given $obj2 an individual identity by assigning the string "widget 5442" to its $name property, before using the -> operator once again to print each object's name property to the screen.

You can use objects to store information, but that makes them only a little more interesting than associative arrays. In the next section, we will look at object methods, and your objects can get a little more active.

    [ Team LiB ] Previous Section Next Section