Property Setter Trait
Trait providing methods to set properties with an array., (*1)
class Foo
{
Use \dgifford\Traits\PropertySetterTrait;
public $string = '';
public $array = [];
public $bool = false;
public $anything;
protected $cannot_be_set;
public function __construct( $properties = [] )
{
/*
Set public properties from $properties array.
Only set properties if they are the same type
by setting the second argument to true.
$anything can be set to any type because it is null.
*/
$this->setPublicProperties( $properties, true );
}
}
$foo = new Foo([
'string' => 'Hello world',
'array' => ['Hello world'],
'bool' => false,
'anything' => 'Hello world',
]);
echo Foo->string; // 'Hello world'
setPublicProperties() can also call a method to set/ validate each property., (*2)
This is achieved by providing a string as the second argument. The string is used as a prefix to generate a method name in the format $prefix . $property_name to set the property., (*3)
If a method doesn't exist for setting the property, the value will be ignored., (*4)
class Foo
{
Use \dgifford\Traits\PropertySetterTrait;
public $string = '';
public $array = [];
public $bool = false;
public $anything;
protected $cannot_be_set;
public function __construct( $properties = [] )
{
/*
Set public properties from $properties array.
Only set properties if they are the same type
by setting the second argument to true.
$anything can be set to any type because it is null.
*/
$this->setPublicProperties( $properties, 'set_' );
}
/**
* Method for setting the $string property.
*/
public function set_string( $value = '' )
{
if( is_string( $value ) )
{
this->string = $value;
}
}
}
$foo = new Foo([
'string' => false,
]);
echo Foo->string; // ''
$foo = new Foo([
'string' => 'Hello world',
]);
echo Foo->string; // 'Hello world'
The trait also has a callAllSetters( $prefix = 'set_' ) method, which will call all methods within the class named using the convention $prefix . PROPERTY_NAME, (*5)
The prefix 'set_' is used by default., (*6)
This can be used to validate properties (e.g. after using setPublicProperties() ) as the current property value is sent to the set method or set defaults dynamically., (*7)
class Foo
{
Use dgifford\Traits\PropertySetterTrait;
public $anything;
protected $protected;
public function set_anything()
{
$this->anything = 'anything';
}
public function set_protected()
{
$this->protected = 'protected';
}
public function getProtected()
{
return $this->protected;
}
}
$foo = new Foo;
$foo->callAllSetters();
echo $foo->anything; // 'anything'
echo $foo->getProtected(); // 'protected'