54

I Want Scalar Objects in PHP

 5 years ago
source link: https://www.tuicool.com/articles/hit/ry2yemF
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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)

* 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:

Fellow #PHP developers, what are the features you would like to be added, changed or removed in 8.0?

— Nikola Poša (@nikolaposa) July 16, 2018

To which I replied:

I’d love scalar objects.

— Matt Sparks (@DevelopmentMatt) July 16, 2018

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!

or

$hello = 'Hello Matt!';
 
var_dump($hello.replace('Matt', 'Bob')); // Hello Bob!

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK