DEV Community

Cover image for I Want Scalar Objects in PHP
Matt Sparks
Matt Sparks

Posted on

I Want Scalar Objects in PHP

Originally Posted on DevelopmentMatt.com

Recently, I read an interesting article from Andrew Carter entitled Make PHP Great Again [cheap plug: this link was included in my most recent Newsletter]. In it Andrew brought up the topic of scalar objects. If you're not familiar with scalar objects, they represent a single value (integer, boolean, string, etc.) that you can perform operations on*. In PHP this could look something like:

$name = 'Matt';

var_dump($name->length()); // int(4)
Enter fullscreen mode Exit fullscreen mode

* It's important to note that, as far as I've been able to ascertain, the context in which you use the term "scalar" is important. Different languages implement and define scalar differently.

Soon after scalar objects were brought to the forefront of my mind, I came across the following tweet:

To which I replied:

The Case For Scalar Objects in PHP

If you read Andrew's post he discusses how PHP's core functions are inconsistent. This topic isn't new:

PHP 8 is a great opportunity to cleanup these inconsistencies. Introducing scalar objects would provide a consistent API that would be more fluent and much more enjoyable to work with. Which of the following is more intuitive to you?

$hello = str_replace('Matt', 'Bob', 'Hello Matt!');

var_dump($hello); // Hello Bob!
Enter fullscreen mode Exit fullscreen mode

or

$hello = 'Hello Matt!';

var_dump($hello->replace('Matt', 'Bob')); // Hello Bob!
Enter fullscreen mode Exit fullscreen mode

I know this is a silly example, but doesn't the second bit of code just feel better?

Let's get scalar objects in PHP 8! Who's with me?!?

#ScalarIn8

Latest comments (33)

Collapse
 
programmingdive profile image
Programming Dive • Edited

Hi Matt, don't you think that posting same content on two places will create chaos in Google search engine because this content is no longer unique on internet

Collapse
 
blackcat_dev profile image
Sasha Blagojevic

I’m with you!

Collapse
 
phlak profile image
Chris Kankiewicz

I have been working on a library for this exact thing. Check it out: twine.phlak.net

Collapse
 
david_j_eddy profile image
David J Eddy

The ability to set type_strict globally for a project. Either via php.ini, composer.json or version used 8.y.z-strict || 8.y.z

I feel like the more type strictness / checking PHP gets the more it is viewed as a professional language (I know, it s BS but it is what I see in around the web).

Function argument order is another one that needs correcting.

Collapse
 
jsebrech profile image
Joeri Sebrechts

When using loosely typed programming languages for very large code bases you end up wishing for namespacing and strict types to enforce isolation and contracts between code modules at the language level. Once you have strict types you quickly figure out you need generics to fully type-check all your code. Once you have generics you realize you can have strictly typed generic collection classes and Maybe types (e.g. java's optional). Once you use those you realize that they'd be awesome if they had fluent API's so you could do collection->map(...)->filter(...)->sort(...)->reduce(...), and so all those collection classes and maybe types are extended to support that style (e.g. java's streams). And then when you're writing that kind of code, it would be awfully handy to have pattern matching and macro-like meta-syntax (see: scala).

And that is how all programming languages used for large projects, including PHP, are on a path to become like haskell, scala, etc. which already have all of these features. It is inevitable.

Collapse
 
kaime profile image
Jaume Alemany

This was already proposed,implemented and rejected a few years ago:

github.com/rossriley/php-scalar-ob...

Looks like now it exists as a PHP extension:

github.com/nikic/scalar_objects

Collapse
 
ianfoulds profile image
Ian Foulds

But this would be so much better if it was part of the core and had properly published methods.

PHP needs to grow and keep up with the needs of developers rather than developers continuously getting frustrated with the lack modernity in one of the most popular languages in use. If PHP does not embrace good OOP practices it will loose it's popularity. Given that .NET Core has been available cross platform for some time now, it is becoming a popular draw for those of us who long for something better. If it were not for a host of projects and a large code base I would have moved on already.

Time will tell and for me time is running out with the arcane state PHP is still in, despite the major leap in PHP 7 it's still very old fashioned.

Collapse
 
hsemix profile image
Hamid Semix

I agree with you 100%, If it wasn't for the large code bases I have to maintain every single day, I would be using .Net Core, but hey, I think the killer feature here would be generics. That is really needed.

Collapse
 
samuraiseoul profile image
Sophie The Lionhart • Edited

Are you proposing this work similar to Java with auto boxing? I mean something like

$var = 'hella clever string here';
$var->someStringMethodHere();
Enter fullscreen mode Exit fullscreen mode

Is cool and all, but are we going to assume auto boxing here or are we going with no more primitives at all? I feel if we still want real primitives(which I assume we do), something like

$var = new String('Even more hella clever string here');
$var->someStringMethodHere();
Enter fullscreen mode Exit fullscreen mode

is a better approach than automatically auto boxing all scalars into objects. That way we have both scalar objects and primitives still.

Perhaps instead even better could be having the 'scalar object' not be a real object at all, but instead the access before in the first example I provided instead be a bit of syntactic sugar for

someStringMethodHere('hella clever string here');
Enter fullscreen mode Exit fullscreen mode

Something like that would be great. Without generics and such I don't think we really want them to be objects cause we wouldn't want something like

function foo(stdClass $obj) : void {
 echo $obj::class;
}
$var = 'scalar string';
foo($var);
Enter fullscreen mode Exit fullscreen mode

Because then there's literally no point to using stdClass as a type hint since everything would be one.

Also I just want a real god damn array. None of this map masquerading as an array bullshit. Sometimes I just need some integers one after the other in memory and not have to worry about if someone used a string as an index by accident.

Collapse
 
theodesp profile image
Theofanis Despoudis

The one and only answer to the original tweet I believe is to remove the dollar sign '$' it's hideous

Collapse
 
samuraiseoul profile image
Sophie The Lionhart

I don't hate the dollar sign per say but I agree it is pretty glaring. But I mean putting a different symbol or the word var or something in front of all the variables wouldn't be much better either. I'm curious about another idea you have for it though!

Collapse
 
ianfoulds profile image
Ian Foulds • Edited

How about prefixing with a strict type?
dev.to/mattsparks/i-want-scalar-ob...

Collapse
 
blackcat_dev profile image
Sasha Blagojevic

I’m with you!!! Um, where should I sign?

Collapse
 
vlasales profile image
Vlastimil Pospichal • Edited
<?php

class Name {
    private $name;

    function __construct($name) {
        $this->name = $name;
    }

    function length() {
        return mb_strlen($this->name, 'UTF-8');
    }

    /* object replace() */
    function ooReplace($needle, $replace) {
        $this->name = str_replace($needle, $replace, $this->name);
        return $this->name;
    }

    /* functional replace() */
    function replace($needle, $replace) {
        return str_replace($needle, $replace, $this->name);
    }

    function __toString() {
        return $this->name;
    }
}

$name = new Name("žluťásek");
var_dump((string) $name);                 // string(11) "žluťásek"
var_dump($name->length());                // int(8)
var_dump($name->replace('ťáse', 'ční'));  // string(10) "žlučník"
var_dump((string) $name);                 // string(11) "žluťásek"
Collapse
 
emkographics profile image
Emko

good stuff, good stuff.

Some comments may only be visible to logged-in visitors. Sign in to view all comments.