igorgue
igorgue

Reputation: 18242

Add attribute to an object in PHP

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

Upvotes: 45

Views: 64367

Answers (4)

Jay Bienvenu
Jay Bienvenu

Reputation: 3293

In PHP 8, attributes are the mechanisms to add structured, machine-readable metadata information on declarations in code: Classes, methods, functions, parameters, properties and class constants can be the target of an attribute. As of PHP 8.3, it apparently is not possible to add an attribute directly to an object unless you declare the object as an anonymous extension of a class.

For example, you can do this:

$my_object = new #[SomeAttribute] class;

but not this:

#[SomeAttribute]
$my_object = //... whatever

What's happening in the legal example is that you aren't adding the attribute to the object itself, but rather the anonymous class you are creating. This will be sufficient for some use cases, but it isn't an assignment of the attribute directly to the object as one might intend to do.

Upvotes: 0

Pekka
Pekka

Reputation: 449395

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.

Upvotes: 76

David Morrow
David Morrow

Reputation: 9354

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 ]; 
}
}

Upvotes: 0

bimbom22
bimbom22

Reputation: 4510

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.

Upvotes: 0

Related Questions