DEV Community

Better strings in PHP

Matthew Daly on July 25, 2018

One of the weaknesses of PHP as a programming language is the limitations of some of the fundamental types. For instance, a string in PHP is a simp...
Collapse
 
davidbruchmann profile image
David Bruchmann

btw: adding a previous() (or prev()) function to the iterator class can make some things a lot of easier. Don't know if it had a usable feature related to the strings here, but it's easy to implement and can save some headaches in other use-cases.

Collapse
 
aleksikauppila profile image
Aleksi Kauppila

Very nice, good job. I like the idea of implementing ArrayAccess here. Using global functions in PHP is a pain in the ass an not OOP at all. It's good to hide all of them into these sort of types.

Collapse
 
matthewbdaly profile image
Matthew Daly • Edited

Another thing I didn't mention in the post is that if you use value objects, you can use something like this as the base class for those, thereby getting all of that functionality easily. For instance, you could extend the custom string class into an Email class that validates the passed string is a valid email address when it's passed to the constructor, and typehint it to ensure that any method that receives an email gets an instance of Email and not just a generic string and it already has the various methods of the string class.

Collapse
 
adhocore profile image
Jitendra

i once wrote a simplistic and minimalist library with that was based on magic. however it was one solution for strings, numbers and arrays alike. 😊