Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add attribute to an object in PHP

Tags:

php

How do you add an attribute to an Object in PHP?

like image 286
igorgue Avatar asked May 17 '10 16:05

igorgue


1 Answers

Well, the general way to add arbitrary properties to an object is:

$object->attributename = value; 

You can, much cleaner, pre-define attributes in your class (PHP 5+ specific, in PHP 4 you would use the old var $attributename)

class baseclass  {     public $attributename;   // can be set from outside    private $attributename;  // can be set only from within this specific class    protected $attributename;  // can be set only from within this class and                               // inherited classes 

this is highly recommended, because you can also document the properties in your class definition.

You can also define getter and setter methods that get called whenever you try to modify an object's property.

like image 111
Pekka Avatar answered Oct 02 '22 12:10

Pekka