Array properties

From Sunhill Framework Documentation
Revision as of 20:50, 28 September 2024 by Klaus (talk | contribs) (Created page with "'''Array properties''' are properties that are accessed like a php array via an index. Array indexed are derived from AbstractArrayProperty which in turn is a child of AbstractProperty and therefor inherits all its properties and methods. But there are some array specific topics: == Accessing an element == Like with any array one can access an element via [$index]. Example: echo $array_property[0]; // prints the first element (when it exists) == Addin...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Array properties are properties that are accessed like a php array via an index. Array indexed are derived from AbstractArrayProperty which in turn is a child of AbstractProperty and therefor inherits all its properties and methods. But there are some array specific topics:

Accessing an element

Like with any array one can access an element via [$index].

Example:

echo $array_property[0]; // prints the first element (when it exists)

Adding an element

A new element is added via the the [] operator.

Example:

$array_property[] = 5; // appends the element 5 to the array.

Replacing an element

A replacement of an element works the same as with php arrays

Example:

$array_property[0] = 10; // Sets the first element to 10

Allowed element types

As an array could not take any element type as an value. An array of integers couldn't accept a string element. Therefor array properties provide the following methods:

setAllowedElementTypes($type_or_types): self

Sets the allowed element. The parameter could be a single string, a class or an array of strings.

Example:

setAllowedElementTypes(TypeString::class); // Only strings are allowed as an element
setAllowedElementTypes($string_property); // The same as above: Only string are allowed
setAllowedElementTypes([TypeString::class, TypeInteger::class]); // Only strings or integers are accepted as an element type

Note: If you call this method repeatedly all given elements are merged together. So

setAllowedElementTypes(TypeString::class);
setAllowedElementTypes(TypeInteger::class);

is the same as

setAllowedAElementTypes([TypeString::class, TypeInteger::class]);

getAllowedElementTypes(): array

Returns an array of types that are allowed as an element type for this property.

Note: An array is even then returned if only one element exists

Empty array and null

There is a difference between an empty array and a null array. While one can access the function count() on an empty array (but of cause no elements) it is not possible for a null array. A new element can be assigned to both.

Example:

$array_property->count(); // would be 0 for an empty array and raises an exception for a null array
$array_property[] = 12; // Would append the element '5' to an empty array and create an array and add a first element to a null array