[6] PHP8 New DateTime objects ‘From’ interface, Stringable interface, and str_contains function
This is the sixth part of the series and in the current post, I want to go through the DateTime objects ‘From’ interface, Stringable interface, and str_contains function. You can see the full list of features here. Furthermore, you can read the fifth part of the series here.
Create DateTime objects from the interface
DateTime::createFromInterface(DateTimeInterface $other);
DateTimeImmutable::createFromInterface(DateTimeInterface $other);
New Stringable interface
The Stringable interface can be used as a type hint to anything that implements __toString(). When we implement the __toString() method that will automatically implement the interface behind the scene.
class Foo
{
public function __toString(): string
{
return 'foo';
}
}
function bar(string|Stringable $stringable) { /* … */ }
bar(new Foo());
bar('abc');
New str_contains function
This function works as the in_array function but it is for Strings. We can check whether the word is in the string expression or not.
if (str_contains('string with lots of words', 'words')) { /* … */ }
Useful Topic related Links
The previous part of the series
PHP 8.0: Allowing class on objects, Non-capturing catches, and Trailing comma in parameter lists