How to explain PHPDoc attributes of `@property-read` and `@property-write`?
✔ Recommended Answer
Here's a good explanation on magic properties.
Basically, @property-write
is interpreted - as the name suggests - as a write-only property. The code completion in Eclipse, for example, makes use of this. If your magic property foo
is declared "write-only", it wouldn't show up in code completion, when you type $a = $this->f
.
Source: stackoverflow.com
Answered By: Linus Kleen
In PHP, @property-read
and @property-write
are two types of PHPDoc attributes that are used to document properties of a class.
@property-read
is used to document properties that can be read (i.e. accessed) by the external code but cannot be written to. It is used to declare a getter method for the property. This attribute is typically used to indicate that the property is read-only and should not be modified directly.
Here is an example of using @property-read
in PHPDoc:
vbnet/**
* MyClass Class
*
* @property-read int $id The ID of the MyClass instance.
*/
class MyClass
{
/**
* Get the ID of the MyClass instance.
*
* @return int
*/
public function getId()
{
// implementation
}
}
In this example, the @property-read
attribute is used to declare that the id
property of the MyClass
class can only be read and not written. The getId()
method is the getter method for the id
property, which returns the value of the property.
@property-write
is used to document properties that can be written to (i.e. modified) by the external code but cannot be read. It is used to declare a setter method for the property. This attribute is typically used to indicate that the property is write-only and should not be accessed directly.
Here is an example of using @property-write
in PHPDoc:
php/**
* MyClass Class
*
* @property-write int $id The ID of the MyClass instance.
*/
class MyClass
{
/**
* Set the ID of the MyClass instance.
*
* @param int $id
*/
public function setId($id)
{
// implementation
}
}
In this example, the @property-write
attribute is used to declare that the id
property of the MyClass
class can only be written to and not read. The setId($id)
method is the setter method for the id
property, which sets the value of the property.
In summary, @property-read
and @property-write
are PHPDoc attributes used to document properties of a class that can be read and written respectively. They are used to declare getter and setter methods for properties to ensure proper encapsulation and to document the accessibility of the properties.
Comments
Post a Comment