How do you add an attribute to an Object in PHP?
Take a look at the php.net documentation: http://www.php.net/manual/en/language.oop5.properties.php
Attributes are referred to as "properties" or "class members" in this case.
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.
this is a static class but, the same principle would go for an intantiated one as well. this lets you store and retrieve whatever you want from this class. and throws an error if you try to get something that is not set.
class Settings{
protected static $_values = array();
public static function write( $varName, $val ){
self::$_values[ $varName ] = $val;
}
public static function read( $varName ){
if( !isset( self::$_values[ $varName ] )){
throw new Exception( $varName . ' does not exist in Settings' );
}
return self::$_values[ $varName ];
}
}