Within PHP, I'd like to be able to iterate over a collection of classes to help with settings, inserting, and validating values. Using a class as a type in method args would make the code more strict which would help avoiding bugs.
I am able to access the collection but only through a public array or method ($values->array
or $values->get()
).
I would like to be able to use $values
directly for cleaner code. For example, to access a reference, I'd need to use $values->array[0]
or $values->get()[0]
instead of $values[0]
. How can this be achieved with PHP?
Expected usage:
$values = new Values(
new Value('foo', 'bar'),
new Value('foo2', 'bar2'),
);
function handleValues(Values $exampleValues): void
{
foreach ($exampleValues as $exampleValue) {
//do something with $exampleValue->field, $exampleValue->value
}
}
handleValues($values);
Classes:
class Values
{
public array $array;
public function __construct(Value... $value){
$this->array = $value;
}
}
class Value
{
public string $field;
public mixed $value;
public function __construct(string $field, mixed $value)
{
$this->field = $field;
$this->value = $value;
}
}