dgifford/property-setter-trait

提供通过数组设置类属性的方法的特质。

v2.0 2021-11-11 11:31 UTC

This package is auto-updated.

Last update: 2024-09-11 18:04:06 UTC


README

提供了一种使用数组设置类属性的方法。

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 sets properties if they are the same type.
			$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'

如果数组中的值与类中默认属性的类型相同,则将使用该值。

自动调用设置器方法


如果不存在设置属性的方法,则会抛出 `BadMethodCallException`

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'

调用所有设置器方法

`callAllSetters()` 方法检索类中的所有属性,并将它们传递给存在的任何设置器方法。

这可以用于更复杂地操作属性(例如,在调用 `setPublicProperties()` 之后)。

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'