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 ...

Get Sams Teach Yourself PHP in 24 Hours, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.