New PHP extension allows adding custom methods to scalars

    A new experimental PHP extension “scalar_objects” has appeared on Github , with which you can add any methods to numbers, strings, arrays.
    It looks something like this:

    $result = $string->replace('shit', 'candy')->remove(',')->toUpper()->split(" ")->sort();

    Pretty, isn't it?
    Installation instructions can be found at the link above, PHP 5.4 is required.
    Keep in mind that the extension is in a very early alpha version, the first commit is dated January 24th.
    I am glad that the author of the extension is the PHP contributor Nikita Popov: there is a possibility that such an API will someday be added to the core of the interpreter.
    Next, I'll just show how you can use these new features in development.

    Let's say we have this line:

    $string = 'lemon, orange, shit, banana, apple';

    • replace shit with candy;
    • remove commas;
    • convert the string to uppercase;
    • separate words and put them in an array;
    • sort this array alphabetically.

    This is usually done like this:

    $string = str_replace('shit', 'candy', $string);
    $string = str_replace(',', '', $string);
    $string = strtoupper($string);
    $array = explode(' ', $string);

    With this extension, the task is solved in one line:

    $result = $string->replace('shit', 'candy')->remove(',')->toUpper()->split(" ")->sort();

    Everything is clear and beautiful, only how to crank it up?
    1. Install the scalar_objects extension;
    2. Create handler classes for strings and arrays with the public methods we need:

        publicfunctionreplace($from, $to){
            return str_replace($from, $to, $this);
        publicfunctionsplit($separator, $limit = PHP_INT_MAX){
            return explode($separator, $this, $limit);
            return strtoupper($this);
        	return$this->replace($what, '');
        publicfunctionsort($flags = SORT_REGULAR){
            sort($this, $flags);
            return count($this);

    3. Bind the methods for strings and arrays to the corresponding classes:

    register_primitive_type_handler('string', 'StringHandler');
    register_primitive_type_handler('array', 'ArrayHandler');

    After that, the string variables got the replace, split, remove methods and so on, the arrays got the count () method. Naturally, you can add as many useful methods as you like. Note that they are all public, and $ this acts as the processed string (array, number). Similarly, handlers can be assigned to any scalar type.
    It should also be noted that designs of the form:


    cause Parse error, that is, methods can only be called on variables so far.
    Also in the repository there is an example of the implementation of a convenient API "string queries":

    // содержит ли строка любую из указанных подстрок?
    $str->contains(str\anyOf(['foo', 'bar', 'hello', 'world']));
    // не заканчивается ли строка любым из этих значений?
    $str->endsWith(str\noneOf(['.c', '.ho', '.lo']));

    It is very clear and much easier to remember, unlike strspn, strcspn, strpbrk.

    I want to believe that PHP developers will include similar functionality in future versions. A little such syntactic sugar will make development much more enjoyable, and developers happier.

    Link to the project:

    Also popular now: