On Mon, Oct 21, 2019 at 5:03 PM Colin O'Dell <colinod...@gmail.com> wrote:
> Hello Internals, > > Is there any particular reason why the substr() function doesn't accept a > null $length like mb_substr() does? It seems the behavior to read through > the end of the string can only be controlled by the presence or absence of > the $length parameter: https://3v4l.org/YpuO1 > > I discovered this discrepancy between the two methods while attempting to > create a specialized string wrapper class with a method like this: > > public function getSubstring(int $start, ?int $length = null): string > { > if ($this->isMultibyte) { > return mb_substr($this->line, $start, $length, > $this->encoding); > } else { > return substr($this->line, $start, $length); > } > } > > This method would not work as expected without additional boilerplate like: > > public function getSubstring (int $start, ?int $length = null): string > { > if ($this->isMultibyte) { > return mb_substr($this->line, $start, $length, > $this->encoding); > } elseif ($length === null) { > return substr($this->line, $start); > } else { > return substr($this->line, $start, $length); > } > } > > Or: > > public function getSubstring (int $start, ?int $length = null): string > { > if ($this->isMultibyte) { > return mb_substr($this->line, $start, $length, > $this->encoding); > } else { > return substr($this->line, $start, $length ?? > (strlen($this->line) - $start)); > } > } > > Are there any historical reasons preventing substr() from accepting a null > $length like mb_substr() does? I'd be happy to write the RFC and take a > stab at the implementation if there's interest in such a change. > This is a fairly common deficiency in the implementation of internal functions. Part of the reason is that historically zend_parse_parameters did not support the ! modifier for integers, and partly these are just implementation oversights. Feel free to send a PR to fix this for PHP 8, no RFC needed. If you're interested in addressing this for more functions, do a grep for "= UNKNOWN" on the codebase, which gives you (with a few exceptions) a list of functions that currently handle null parameters incorrectly and should ideally be fixed for PHP 8. Nikita