Adam Biro

Software Developer

Blogger

Photographer

Full Stack Developer

Photo Enthusiast

Web Developer

Adam Biro
Adam Biro

Software Developer

Blogger

Photographer

Full Stack Developer

Photo Enthusiast

Web Developer

Blog Post

[6] PHP8 New DateTime objects ‘From’ interface, Stringable interface, and str_contains function

April 28, 2022 IT, PHP, Programming
[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')) { /* … */ }
Taggs:
Write a comment