Add new property to object php
In PHP, you can add a new property to an object using the following methods:
- Dynamic property: You can add a new property to an object using the
->
operator. For example:class Person { public $name; }
$person = new Person(); $person->age = 30; // adds a new property "age" with value 30
This method is known as dynamic property, because the property is created on the fly.
2. **__set() method**: You can also add a new property to an object by overriding the `__set()` method in the class. This method is called when you try to set a property that does not exist. For example:
```php
class Person {
private $name;
public function __set($property, $value) {
$this->$property = $value;
}
}
$person = new Person();
$person->age = 30; // calls __set() method and adds a new property "age" with value 30
- Reflection: You can also add a new property to an object using the
ReflectionClass
andReflectionProperty
classes. For example:$person = new Person(); $reflectionClass = new ReflectionClass($person); $property = $reflectionClass->getProperty('age'); $property->setAccessible(true); $property->setValue($person, 30);
Note that the
__set()
method and theReflection
approach are more flexible and powerful, as they allow you to add properties with custom logic and validation.
It's also important to note that when you add a new property to an object, it will not be serialized (i.e., saved to a file or database) unless you explicitly define it in the class or use a serialization mechanism like json_encode()
or serialize()
.