'Dealing with objects without interfaces in PHP8
PHP has the possibility to define interfaces as well as abstract classes for classes. However, it is not possible to define interfaces for objects, as in Typescript.
Therefore, the question I have is how best to deal with objects in PHP. Is there an alternative to Object interfaces?
Example:
A function that creates a new instance of the class Filter.
I need to check if the needed keys exist and check if their types are correct.
function createFilter(array $options): Filter|false
{
$property = null; // string | array
if (array_key_exists('property', $options) && (is_string($options['property']) || is_array($options['property']))) {
$property = $options['property'];
}
$type = null; // string
if (array_key_exists('type', $options) && is_string($options['type'])) {
$type = $options['type'];
}
$value = null; // float
if (array_key_exists('value', $options) && is_float($options['value'])) {
$value = $options['value'];
}
if ($property === null || $type === null || $value === null) return false;
return new Filter($property, $type, $value);
}
At the end of the function, I see two possibilities:
- Return False if the filter could not be created.
- return the class instance if the filter could be created
or:
- Always return the class instance. However, default values would then be used for the values that were not correctly created in
$options
As said, currently there are no object interfaces in PHP. What is the current state of the art on how to best solve the above problem in PHP8?
Edit: Typescript
type FilterOptions = {
property: string|string[],
filterType: string,
value: number
}
class Filter{
constructor(property: string|string[], filterType: string, value: number){
// ...
}
}
const createFilter = (options : FilterOptions) : Filter => {
return new Filter(options.property, options.filterType, options.value);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
