This past weekend, I decided I wanted to bring one of my favourite shortcuts
in Python to PHP strings: its slice notation. Limiting myself to userland
code, there wasn’t much I could do to replicate the syntax. Implementing the
ArrayAccess interface would allow me to overload array dimensions in a
class, though I’d be stuck parsing string offsets for the necessary arguments.
My first attempt, writing only from how I remembered using the slice notation, got me half way there. It handled start and stop well in the case of positive steps, but failed to handle a variety of negative steps. It was a simple mistake, as I wasn’t handling all possible adjustments to the slice boundaries. After looking at CPython’s implementation, I was able to spot where I went wrong and hopefully achieve an implementation that mimics Python’s own behaviour. Here’s a small preview of its use:Read on →