Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
PHP RFC: Deprecate ${} string interpolation (php.net)
81 points by gslin on May 6, 2022 | hide | past | favorite | 90 comments


Having used PHP a long time ago, this is very confusing to me. I would have thought that "${var}" does exactly the same as "$var", but being usable in more cases. For example if you want to append text without a space: "${var}moretext". This is how it works in Bash, at least.

I am really surprized that braces on the outside works at all. I would have expected "{$var}" to expand to "{FOO}".

I thought the version with parentheses is some new general-expression syntax, like "${( $foo + 2 )}" - but that doesn't seem to exist. I would have expected "${(var)}" to give a warning, like the classic "`var` is not a constant. You should use `$var`. Accessing `var` without `$` will stop working in a future version of PHP". (As I said, I used PHP a long time ago...).

PHP is indeed still "a fractal of bad design" :-D, because it gives you the illusion of being able to come back and pick it up easily. But everything does something slightly different than you expect. I commend the PHP devs for removing the footguns and making it a nicer language again!

Personally, I would have removed #2 and #4 - keeping only "$foo" and "${foo}" as equivalent, just like in Bash. And when they get a general expression syntax - maybe "$(foo)" like in Bash, or something else - then you get variable variables back for free.


As someone who uses PHP nearly every working day, this RFC is the first time I've ever seen the ${var} syntax in PHP. It only gets a very brief mention and a single use in an example snippet in the documentation[1]. I don't think I've ever seen it in production code, and would have flagged it as a typo if I found it during code review.

Removing {$var}, on the other hand, would have broken practically every string interpolation I've ever written, and probably about 50% of all uses of string interpolation in the ecosystem.

[1]: https://www.php.net/manual/en/language.types.string.php#lang...


The ${var} syntax has always been my preferred approach. In all the editors I’ve used it syntax highlights as if you had typed “.$var.”, rather than just displaying $var in bold and same colour as the string literal. Plus it allows for more flexible use of arrays or objects

Sad to see the way PHP is killing backwards compatibility. There has always been a way to bodge it with previous BC breaks like removal of mysql and mcrypt, but this isn’t fixable without code changes. I don’t even see any advantage, seems like change for the sake of change


Again? Has it ever been a nice language?


For throwing a little web page together with a small amount of dynamicism, or for including headers and footers, PHP was great. For learning, it had just the right amount of power vs. ease of use.

Of course, PHP has all the well known crazyness and technical debt that drove many away. I now prefer Python, although the same thing is often a lot more verbose in Python than in classic PHP, I know I can maintain it better. "Modern" PHP with classes, stricter typing and templating engines is close, but it loses the easyness of drop-in `<?php ?>` .

Incidentally, I worked on a Wordpress site recently. It was a blast from the past and not in a good way. The coding conventions have not changed in decades, and it is `<?php ?>` and global variables all the way.


I worked on a Wordpress site a few years go, having to add a fair amount of plugins to spin up an MVP of a product we were testing. The incredibly goofy code I saw in those plugins was shocking. Things that should never have made it to production were in there; commented out blocks of code, TODO lines, random log output, complete nonsense comments.

Granted, I shouldn't throw the first stone - at least they didn't commit any obvious profanities, like I did when I was young. But it was just ... very clearly output very quickly.


Go write a better plugin if you've got a problem with it.

The users don't give a shit about any of those things.

The hate on WordPress and PHP by developers here astounds me. WordPress actually gives a shit about backwards compatibility. Unlike literally every modern JS or PHP framework I've used over the last decade has been an utter cluster fuck to keep in production.

Those WordPress websites I set up 10 years ago? Turn on auto updates and forget about it. Maybe 1-2 times I've had to resolve something on them.

Those react, Angular, Vue, laravel, express sites? They lasted a year before npm stopped being able to build updates hell they couldnt even build from a "lock file" (my fuckin ass it is).

What a waste of fucking time. All cause some dipshit kid thinks his "better" way of doing something is worth my time to update my websites.


This seems like a bit of an angry response. I write a lot of Wordpress and php code and help manage one of the most sold themes on theme forest. Php really was, in my opinion, a hell hole of a failed language until 6ish. The patterns people used as standard practice were 5-10 years out of date either due to the slow progress of WP or the php language and ecosystem. A lot of the flack PHP and Wordpress has gotten is totally deserved. Yeah it can just work, but at what cost? Maintenance and upgrading is terrible. Security vulnerabilities galore. You seem involved in WP but just work is a load of bullshit. Everytime we push an update people migrating are walking through a minefield: CSS overlaps, JS import overlaps, php bugs from other plugins. Going back, we can’t even use features from modern PHP because most of our users php versions aren’t well up to date.

Wordpress itself has done a terrible job halfbaking different systems as part of WP core. Gutenberg, imo, is just another abject failure that will take 5 years and provide a buggy solution. You are spot on with the compatibility argument which also has lots of pros and cons obviously.

Also for most js websites built at a certain time things weren’t using npm and bundles and you can simply link the js src like it’s 1999. Just save the source code and you never have to update.

I know this is a trope here but every job has the right tool. WP and php are great tools, especially PHP right now, it has literally never been better. WP on the other hand is just totally confused with Gutenberg and it’s clear Automatic has no idea what they’re doing and who their audience is.


As a full-time WordPress developer, I often do "go write a better plugin" when I have a problem with it. But that doesn't mean it's incorrect to say

> The incredibly goofy code I saw in those plugins was shocking. Things that should never have made it to production were in there

And the owners do

> give a shit about [many] of those things.

because the checkout will start to fail silently. One time for us, customers couldn't check out unless they entered an apartment number.

The standard of code in the WordPress ecosystem is sub-par.

Unit testing, static analysis and linting are NOT the norm.

Part of my routine is to read the error logs, fix the rookie mistakes introduced in plugin updates, and send the fixes back upstream. And when I say send, I mean email them or open a support thread on WordPress.org. It's a blessed day when the plugin is on GitHub for me to make a PR.


I write PHP, and I was shocked when I have to write WordPress plugin for the first time.

The forms API in WordPress, for example, require you to output HTml directly from the callback function.

Granted, it was a design that make sense 15 years ago, but I would have though there would be newer API.

It work fine, sure, but doesn't mean I have to like it.


When your preferred PHP alternative has produced as many open source killer apps, in terms of adoption, as PHP has I'll be all ears.


These two lines of code are now deprecated, and will be removed in PHP 9.0. My question is: what will they do in PHP 9.0? Will they throw a syntax error? Or will they print something else?

  echo("${foo}"); // Will this print '${foo}' in PHP 9.0, or will it raise a syntax error?
  echo("${(foo)}"); // Will this print '${(foo)}' in PHP 9.0, or will it raise a syntax error?
Personally, I would prefer it to raise a syntax error. Otherwise, code that runs one way in PHP < 9.0 will run a different way in PHP 9.0, failing silently. I would prefer it to fail loudly.


Even worse, it will reveal the variables used by your page to the user, which in some cases can be a security risk.

I assume it will raise a syntax error, as the PHP team is good about these things.


But that's also stupid because you cannot actually simplify the parser that much then, as you still need to detect it. And then you could just keep supporting it anyways, since it pretty much calls into the same code as the surrounding curly braces after that.


I mean, you could just set the parser to throw an exception if it ever detects anything other than a character (a-zA-Z) after an un-escaped dollar sign. Then you can just throw the same error, "Invalid string interpolation" so that no internal state of your program leaks, and you can immediately skip any subsequent memory reads for the contents of the variable.


A syntax error would be \s fun though, would you have to escape the sequence in order to get that intentionally?


If you have display_errors on, you have much security risk than this.


If you set error reporting to E_ALL I assume you will get a 'undefined variable {foo}'.

Which I think will be loud enough.


Personally, I would prefer if they just left working code alone.


Don't panic: this deprecates `${var}`, which is a less-common syntax for interpolation, but leaves the most common ones, `$var` and `{$var}`, in place.

It reduces the number of slightly different ways to do one thing, and clears the ground for adding any-expression interpolation, which PHP is currently missing.


I'm not worried about the deprecation itself. I'm worried about the second argument you're making. This RFC trades stability for nicer syntax that isn't really needed. PHP is already great with strings. If the deprecation was indefinite and there wasn't a language feature waiting that relies on removing this, then I would not be worried at all. Will the implications be bad in this case? Probably not? It's the mentality behind that makes me uneasy.


PHP has been modernising for years. This particular change feels like a bad move to me (pointless) but it's part in parcel with them modernising overall and I don't want to discourage that as most of the improvements have been extremely beneficial. Speed upgrade from 5 to 7 was insane.


I've never known that "{$var}" was even allowed. All other languages using $ for string interpolation use the "${var}" pattern, often also allowing any expression ("${var / 10 + 2}") within the brackets.

Keeping "{$var}" seems like a strange decision to me. I assume the people who made the decision analysed open source projects and evaluated which option gets used most, but it doesn't feel like the most obvious decision to me.


You'd have to rewrite a good portion of all existing PHP code to eliminate the "{$var}" syntax. It is the "right" way to include variables in a string.


PHPStorm/PHPStan (I'm not certain which) will tell me `"My {$var} string"` doesn't need the `{}`, but won't give me the same notice when using `"My {$obj->getVar()} string"`. Personally, I prefer keeping the `{}`.


"{$arr[2]}" for array and object, {} is required.


But why remove it in the first place. Is it such a burden on the parser or mental overhead for developers?


Because this syntax is used for variable variables as well as interpolation.

By removing the interpolation, it makes the remaining code more predictable and less likely to have a footgun.


> clears the ground for adding any-expression interpolation, which PHP is currently missing


I don't like such changes. Php 8 had a lot of breaking changes and upgrading it is already an arduous task. If I don't upgrade then package will demand php 8. If I don't upgrade package & language then I must stay alert of security vulnerabilities. And, changes like this makes relearning difficult. I wonder why majority of people in rfc voted "yes"

Thankfully I am investing in Rust language which has stability guarantee. In my opinion language shouldn't move fast. There should be balance. All those tutorials, guides become useless. There is a reason why COBOL is still used for 90%+ atm swipes.


There should be the php equivalent of LTS (long term support). After such a long time on php 5.. it felt like one of the features of the language was stability. Your old code ran. 7 was much faster so easy sell to upgrade. the versions obsolescence treadmill has begun.. I like the language but having to upgrade this frequently (every couple years) is a bit much.

https://www.php.net/supported-versions.php


We should just stop messing with it. PHP is what it is, if you want something better/different build another HACK.

At this point the language works and works well. Everyone knows where the sharp edges are. The only people who are unhappy are the people who are forced into being PHP devs by $dayjob and would prefer a different language.


You are extremely mistaken. I love PHP and am quite happy with how it's evolving into a more concise and well defined language.

If you don't like it you are free to continue using an old version.

Expecting a language to stagnate because you don't like learning new things is asinine and doesn't hold water anywhere in the programming world except among the laziest of code monkeys.


You mean being forced into being PHP devs by ${dayjob}... ;-)


slow clap


> Php 8 had a lot of breaking changes and upgrading it is already an arduous task.

How so? I've upgraded most of my project to PHP 8 quite easily. Which versions were you running before, and what breaking changes did you see?


Not OP, but the only one that I know of and that can trip you up without giving any form of warning is the change of resources types to class types for some of the libraries, like curl.

Thus if your old code did a check like is_resource it will now return false instead of true.


> Thankfully I am investing in Rust language which has stability guarantee

For 25 years? Because that’s the timeline we’re talking about for PHP. There’s cruft after 25 years that should be cleaned out. Java is doing the same (but slower, and there’s less cruft).

You seriously think Rust or any language doesn’t need to change backwards compatibility for 25 years?


If you are using PhpStorm you can run a code analysis for a PHP version.

I did this on a large project made for PHP 7.2, including the vendor folder. The changes I had to make were minimal and were done within half an hour.

If this makes the language better, why not?


Can you tell me what in PHP 8 you're struggling with? Pretty much everything listed here has been deprecated for a long time or used by almost nobody: https://www.php.net/manual/en/migration80.incompatible.php

I've made my whole career about PHP and had no idea it supported stuff like (uncast).


In almost two decades of PHP programming, I can remember that I was 'forced' by a webhost to update my code only once. They went from PHP5 to PHP7 - if I recall correctly - and I had to change some MySQL function calls to MySQL PDO.

It was slightly more work than changing function calls, but if my code had been object oriented at that time, it would have cost me one hour max. Your mileage may vary for bigger code bases.

Edit: okay, make that two hours.


I see many aren't familiar with https://github.com/RectorPHP/Rector . It will help you with a bunch of PHP&frameworks migration work.


> This RFC proposes to deprecate options 3 and 4 in PHP 8.2 and remove them in PHP 9.0.

Why remove it? Why break everyone when you can just deprecate it indefinitely or at least for a very long time?

Deprecated it, write clear warning messages with links to official docs, suggesting alternatives. Update official docs to reflect the idioms. Done.

PHP as a language and ecosystem seems to be evolving backwards from a reliable, productive and accessible tool to something that is breaking callers, introduces versioning and upgrade issues.

And it's already harder to debug than competing languages, because errors are spread across the server, the language runtime and even within that there's different types of error systems with error reporting, exceptions, error values and so on.

I'm impressed by some of the improvements that PHP went through and there are some rock solid tools and libraries (the star here is composer) but at the same time I feel less and less confident using it from a stability perspective.


PHP seems to be doing better and better with tooling since the plethora of changes got gradually added.

Due to the introduction of better types support; psalm, phpstan, can statically analyze your PHP code and surface bugs that you might overlook in the past. Of course this is what static typing programmers have been preaching all along, but you don't have to go all in, some gradual typing is enough to get benefits.

Ok, you don't want to use the extra type support that PHP nowadays has, you can still benefit from it. Tools like https://github.com/RectorPHP/Rector help you automate PHP code updates, and changes between framework versions. Even the linked proposal includes a script based around the recent-ish PHP built-in tokenizer (no regex shenanigans), to migrate the code for you.

There's some churn, but generally deprecations are sensible. I'm also active in other language communities and deprecation paces are comparable IMO.


> errors are spread across the server, the language runtime and even within that there's different types of error systems with error reporting, exceptions, error values and so on.

To the best of my knowledge, errors are not spread across anywhere; server errors have nothing to do with PHP, and would happen regardless of the backend language you're using.

As for different types of errors, the PHP team has been hard at work moving -everything- over to exceptions. It's precisely because they're willing to remove old/obscure/confusing parts of the language and clean the syntax up, that it has been able to evolve into the fast & modern language it is today.


> PHP as a language and ecosystem seems to be evolving backwards from a reliable, productive and accessible tool to something that is breaking callers, introduces versioning and upgrade issues.

Having 7 different methods to do string interpolation is not "productive and accessible", it's confusing and prone to abuse.

The whole "never break user land/space" axiom that the PHP core used to follow isn't healthy for the language, and I'm glad we're moving away from it.

I want PHP to grow into a more modern and stricter language, and I can understand that iterating fast and deprecating old behavior is part of that evolution.


> The whole "never break user land/space" axiom that the PHP core used to follow isn't healthy for the language

I would say it's not healthy for most languages.


Perhaps it can also be renamed "SHP" (strict homepage processor)

Why would anyone prefer a tool dead set on undoing their productive investments with each new release? Decisions like this are a massive red flag. It doesn't allow the feature to be removed (interpolation still exists and isn't going away), I doubt it simplifies the code much, it just breaks existing projects out of essentially a stylistic preference. That's not a tool I'd ever want to depend on


Did you read the full RFC? It's not strictly 'stylistic preference' as each version has slightly different capabilities and there's potential ambiguity between some of those capabilities.


Big fan and longtime user of PHP here. Personal code has been providing business value with hardly any changes for 10 years. What has burned me recently is BoltCMS 3 using lots of symfony packages that don't work on PHP 8 anymore. There's a new version of the CMS, but it's a rewrite meaning lots of work to rewrite extensions and customization. Really grateful for the good open source CMS and PHP, but it's hard to sell customers an expensive update that won't give them any visible benefits. Those customers might decide to spend the money to build a new website with somebody else instead. PHP5 and 7 were quite backwards compatible, but sadly PHP8 seems to break a lot. New versions are supported for a much shorter time now.

So while I still like PHP and the good work they are doing, the maintenance cost has sadly steeply risen recently. SLAs are a necessity now.


With dynamic language like PHP where there is no traditional compilation step by the programmer, these new deprecations will lead to lot of subtle bugs to be found in production.

This was to certain extent the same problem with Python 2.0 -> Python 3.0 changes. I remember not liking the process with that, however I understand the need to deprecate some features for performance etc.

PHP should have built-in tool to scan source code for likely deprecations, there are third party tools but I haven't tried those. Given that there is a lot of code with PHP whom nobody anymore really bother to maintain, but it still has to work, it would be beneficial.


Thanks for sharing this. It's good to remember that even relatively pragmatic languages like PHP often deprecate syntax features simply because they're "inferior" to another syntax feature.


Well, PHP approach to features is not really "pragmatic", it has boiled down for decades to basically adding whatever they could rip from somewhere else, without the slightest trace of logic behind it. When they deprecated and removed mysql_* way way more impactful IMHO, it basically broke half of the websites on the web. Was it worth it? Absolutely yes, because mysql_* functions were utter garbage and have caused unmeasurable damage over the years with their shoddy approach to sanitizing. Sometimes you have to atone for your sins, and that's what PHP has been doing in the last few releases.


> When they deprecated and removed mysql_* way way more impactful IMHO.

Also folks just moved onto mysqli_* and reused the exact same footgun.


They've been doing that since 5.2


PHP has a strange identity problem. For a language that most would agree is used due to past popularity, it has a lot of breaking changes. But while syntax gets deprecated and function signatures changed, the stdlib is still a mess. The original randomly long functions are still there with no replacement in sight. To make my point, there's still no reasonable int parsing function!

I'm not against change, but PHP devs should decide if they want to make code maintenance easier, or make PHP an actually good language. Right now, it's in a weird in-between state. I'm not a fan of coming across old PHP code and having to make a bunch of small changes to port it to supported PHP.


Well, they basically took the __looks__ of Perl and bolted on a dynamically typed Java on top of it. I don't think there are languages more different in concepts and values than Perl and Java, and PHP is the result of that unholy mixture. Perl is crazy, but it has a very precise logic behind the madness. Java is boring and predictable. PHP is crazy while being completely random.


This is a good summary of PHP in the past and maybe the present. I think the PHP 10 years from now won’t have the craziness anymore, based on the current trend.


They've gotten more aggressive lately in wiping away the dusty corners of the language, little-used alternative syntaxes like these,some of the footguns. But nothing even approaching a full reorg/rename of the stdlib.

I think the sense is doing something like that would get you into an undesirable "Python 3" type scenario. Instead, the sort of unceasing wave of deprecations leads to some make-work but doesn't seem to cause the same kind of long term resistance to updating.


> But nothing even approaching a full reorg/rename of the stdlib.

It's been a long tradition in the PHP world to keep the PHP side of a module somewhat consistent with the underlying C API that the module exposes.

On the one side, people with a C background immediately find themselves at home in PHP - on the other side, "new" programmers coming from the Java, Go or the matured JS world are confused because of all the inconsistencies.


They pretty much already had the "Python 3" issue with PHP 6, the unicode PHP


Yeah, but it never came out. A bullet dodged.


> there’s still no reasonable int parsing function!

Well, I suppose it depends on how one defines “reasonable”, and perhaps how one defines “parsing” (e.g., what is it you’re trying to do). As a comment elsewhere observed, while

    (int)$val;
will force a non-integer $val to be 0, if what you’re trying to do is determine whether $val is a string literal that represents an integer, you can use

    filter($val, FILTER_VALIDATE_INT);
instead. That will return the integer if it is, and false (actual boolean false) if it isn’t.

Is this the best way to do it? Probably not. But I think I’m okay with testing that filter in an if statement rather than wrapping the type casting in a try/catch block.

However:

> I'm not against change, but PHP devs should decide if they want to make code maintenance easier, or make PHP an actually good language. Right now, it's in a weird in-between state. I'm not a fan of coming across old PHP code and having to make a bunch of small changes to port it to supported PHP.

If the dichotomy you pose in the first part is correct, then “coming across old PHP code and having to make small changes” is unavoidable if they’re striving for the latter. Given that they’re clearly not down for making radical changes that break everything everywhere all at once, then it’s going to be in a “weird in-between state” for years, isn’t it?


stdlib will never change, because it would break every PHP project out there. Many of the previous deprecations as been relatively easy to handle, like switch from each to foreach, or make sure that you don't pass null to stdlib functions, but changing the stdlib itself would instead be a complete nightmare.

Remember that many projects out there needs to support multiple PHP versions at the same time, it would be extremely confusing if the stdlib started to do subtle changes between versions and also hard to properly handle and detect.

Like if you would swap $needle and $haystack for strpos(), it would be nightmarish to statically detect in an existing code base which is the correct order and quite hard for a human.

Introducing aliases is also a bad idea, there already exists aliases in the stdlib and they only add confusion when reading code, that would be true for new aliases as well.

Named arguments alleviates the problem with argument order in exchange for more verbosity.

What PHP could do is to introduce primitive objects, e.g. $str->substr(...), however that would not guarantee a well designed standard library either, because RFC:s and emails is not a good forum for designing API:s.

I think the correct solution is to implement operator overloading and let the community design a standard library/libraries. Because of the massive performance improvements of PHP the standard library is no longer required to be pure C, it can either be implemented in PHP or wrap the existing stdlib.


Lib functions are vertically consistent with the underlying libraries.

https://youtu.be/nmD1Q4FsXCc?t=845


Yeah, PHP sometimes pretends it's a C derivative. I think it's a stupid idea most of the time, especially with regard to strings. C string handling isn't anything scripting languages should copy.

Besides, PHP now has its own (partly duplicate) class-based stdlib for some things, why not be consistent and "replace" all of the old stdlib?


> C string handling isn't anything scripting languages should copy.

Or C-like imports, it's ridiculous tbh, inlcude, inlcude_once, require, require_once.

My understanding is that PHP started as a basic templating language, a way to embed c function calls as tags in HTML.

In that way it's ingenious, people keep reinventing it with JSX, filesystem routing etc. Right now I'm thinking PHP should've gone the other way. Instead of adopting features to resemble other general purpose languages (things like classes from java and so on) it should've doubled down on web stuff, like JSX - in the sense of having a nice syntax for partials/components, eg <php-component props /> instead of <?php echo php_component(props) ?> and other comfort features, to become a platform.


>there's still no reasonable int parsing function

What's wrong with (int)$val ?


There's no error handling, (int)"x" === 0.


You can kind of get this to happen in 8 and up: Doing math on a non numeric string is then a catchable TypeError so you can do 'x' + 0 in a try.

Doesn't avoid other PHP numeric-string stuff like scientific notation and floats being accepted, though. Passing to a int-typehinted function param in 8.1 gets you closer (will complain about float strings) but is currently just a annoying-to-work-with deprecation notice. Presumably it will eventually also be a TypeError.


You should use the filter functions for that


Why should that be an error? First we are explicitly forcing a string to an integer and then comparing it with type sensitivity to another integer.


We could debate that for a long time, but my point was different: There's no sane function in today's PHP that parses ints and handles errors (defaulting to 0 doesn't count).


    /**
     * Cast to int, fail if not a valid integer
     * @throws \UnexpectedValueException
     * @param mixed $thing
     * @return int
     */
    function as_int($thing): int                                                                                             
    {                                                                                                                        
        if (!filter_var($thing, \FILTER_VALIDATE_INT))                                                                       
            throw new \UnexpectedValueException("Value is not an integer.");                                                 
        return (int)$thing;                                                                                                  
    }
While, yeah, it'd be nice if there were something like this built in... it's a couple lines of code. If that's your major complaint, I'd be happy to whip up a whole suite of proper functions to cast to primitives while throwing errors on invalid values since it's just swapping FILTER_VALIDATE_INT for the various types.


I think this illustrates my problem with PHP well: There are ways to do common tasks properly, but they're often hidden, obscure or basically require creating your own "stdlib extension", as seen here (I only heard about filter_var from this discussion, and I specifically searched for string conversion functions).

Your function proves my point: It looks correct, but actually breaks for as_int("0"), since filter_var with FILTER_VALIDATE_INT doesn't acutally validate the int, but parse it, and zero is falsy.


Above usage of filter_var is wrong, there is no need to cast $thing to int, filter_var already returns the filtered int or false on failure. The correct usage is therefore

    /**
     * Cast to int, fail if not a valid integer
     * @throws \UnexpectedValueException
     * @param mixed $thing
     * @return int
     */
    function as_int($thing): int                                                                                             
    {   
       $int = filter_var($thing, \FILTER_VALIDATE_INT);
       if ($int === false) {
         throw new \UnexpectedValueException("Value is not an integer.");
       }
       return $int;
    }
Thus the critique against PHP that is lacks a proper integer parsing function is simply not true, filter_var has been part of PHP since 5.2 released in 2006, over 16 years ago. filter_var works as advertised, because I use it almost every time i write PHP and that is to mostly to parse integers but sometimes also for other types. And I don't even wrap it with my own as_int function, using it inline with an simple if-check afterwards is actually cleaner. And if you prefer that filter_var returns null on failure instead of false you can simply add FILTER_NULL_ON_FAILURE as the third argument to filter_var.

And this is the recurring thing with PHP critique, vast majority of the time it just in imagination because nobody bothers to look it up.

https://www.php.net/manual/en/function.filter-var.php


> And this is the recurring thing with PHP critique, vast majority of the time it just in imagination because nobody bothers to look it up.

I see this from the other side: Good languages guide programmers toward good solutions. Criticism of the simplest or obvious solution is valid, because the language determines what that solution is.

Conversely, arguing that it's possible to write good code is largely meaningless. It doesn't mean that the language is good, just that it isn't completely unfit for purpose. Just look at the number of people who commented about other int parsing methods: Are they bad programmers, because they didn't know to look for filter_var when parsing ints, or is PHP a bad language because something so simple is hard to find a solution for?


Why so many failed to answer this questions is probably due to multiple reasons, here are a few

1) Some programmers are just either too lazy or too arrogant to read the manual, thus bad programmers. As a senior programmer that has helped numerous juniors in their work, this is probably one of the most common mistakes I see, they write code without checking how the API works, or they ask me why something isn't working when it can be easily found in the manual. This is not specific to PHP and I have seen this in everything from PHP to C++.

2) PHP is dynamic language, similar to JavaScript, types were not something you historically bothered with, thus parsing to int is not something the community has a large shared knowledge about, similar how it is rare in JavaScript. However with the introduction of primitive type hinting it has become more common to do proper parsing, hopefully PHP programmers will learn eventually. Thus it is a thing with dynamic languages, not specific to PHP.

3) Why can't programmers find the filter_var method in the manual and/or in the standard library? This I considered as valid criticism of PHP, the standard library is not structured because of the C like flat structure and many of the stdlib functions are weirdly named, like filter_var, what is filter to begin with?

The solution is to build a better stdlib, not throw out the language. I think the community can build a well designed stdlib if PHP implements operator overloading. The performance issues is no longer valid, PHP 7+ has great performance, thus worrying about losing important cycles is not really true anymore.

PHP as a language works well to build good solutions, I have done so in many projects. The critique here evolves around the stdlib, that is not something new.


The stdlib is part of the language, and while theoretically someone could take PHP and pair it with a new standard library, they could also take the PHP VM and pair it with a new syntax and parser with not much more effort. Just as its standard library is one of Python's biggest strengths and almost lacking one is one of JavaScript's biggest faults. Even if a community project is created to replace PHP's stdlib and offer a better alternative, unless everyone adopts it, it will always be just a niche alternative.

PHP needs to actually have a good standard library in its default distribution. Maybe looking to large frameworks like Symfony to develop one isn't a bad idea, but they've largely left the stdlib alone, so just waiting for them to start developing a complete replacement isn't going to work.

(For all its faults, JS' parseInt function is perfectly serviceable, but that's beside the point.)


My proposal would be to let the community build a stdlib and after it is battle tested merge it with core PHP.

It has been proposed before to have PHP source shipped with PHP (and also the possibility mix C and PHP) and think that would be the best option.

One option could be to have slower evolved stdlib in core and a faster community version with composer.

Reason why I’m proposing to develop it outside of core is because a rfc based process is not necessarily the best approach to design a good & well functioning api (and empirically that is true).

It is better to deliver a complete stdlib (or major sub parts) as one or multiple rfc.

And by doing like this you allocate resources better, the few with knowledge about PHP internals can keep focusing on that while the community, a much larger group, can design a stdlib.

And PHP has done a lot of great work on making user land and stdlib on equal footing, so now you can implement strpos(…) to exactly match the stdlib version thanks to union types, similar argument parsing and using same type rules (type errors) between the too.

Only major thing I know of that differs when exposing an api, that is either from a PHP C extension or PHP code, is operator overloading.

A rfc proposal to add it was unfortunate declined, but I’m hopeful that on day it will be added in some form because of this reason, it ought to be possible to express the same intent regardless if it is from C or PHP.

With user land operator overloading we can implement object based primitives with methods instead of the current function based approach. And it could be possible to extend it.

Other nice things you could do is to implement safe and unsafe string handling to avoid injections.

With operator overloading the community can evolve the language without the need to evolve PHP itself.


> defaulting to 0 doesn't count

Why this arbitrary restriction? A forced cast of a string to integer is always guaranteed to produce an integer.


And a forced cast is therefore a bad way to generally parse a user-provided string to int.


So why do you insist on using it that way?


I don't. I asked for an int parsing function, got (int)$val as a suggestion, so I had to explain why it doesn't fit the bill.


And how are we supposed to distinguish that from a legit 0?


is_numeric() has been available since forever, and is intended for exactly the thing you appear to want to do.

https://www.php.net/manual/en/function.is-numeric.php


At this point you're writing the parser that ships in most language's standard libraries.

And, if you naïvely use the suggested function for the purpose you've suggested it for, e.g., like,

  if(!is_numeric($input)) { error(); }
  else { return (int)$input; }
…you'll parse a lot of strings that still aren't valid integers. (E.g., "2e-2" is "numeric" and would thus parse.)


I think that in that case it should return false instead of 0 so (int)$val === false means that the variable is not a number.

Right now I guess that the alternative is using is_numeric and then casting to int if possible.


But the forced cast to integer is always guaranteed to result in an integer. So why would it make more sense to explicitly force cast a variable's type to an integer and get a boolean as the functions return value?

Edit:

> (int)$val === false

Would always be false because comparing two types, an integer and boolean would always be false.


Deprecat PHP.




Consider applying for YC's Fall 2025 batch! Applications are open till Aug 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: