Limiting Access to Object Properties

PHP 4 provided no protection for object properties. Client code could get or set object properties at will. So what’s wrong with that? Often, there is no problem having publicly accessible properties, although it is generally good practice to narrow access to your objects as much as possible. In Listing 9.5, we can see a condition in which we would definitely want to limit access to the $name property in our Item class.

Listing 9.5. A Class with Public Properties
 1: <?php 2: class item { 3: var $name; 4: var $code; 5: var $productString; 6: 7: function Item( $name="item", $code=0 ) { 8: $this->name = $name; 9: $this->code = $code; 10: $this->setName( $name ); 11: } 12: 13: function getProductString () { ...

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.