top | item 22220564

New in PHP 8

326 points| jonifico | 6 years ago |stitcher.io

255 comments

order
[+] ksec|6 years ago|reply
At these rate of improvement, along with Laravel, may be I should seriously evaluate moving back to PHP stack. It was only the other day Antirez, author of Redis [1] was complaining the Ruby Stack is more complicated than it should be. And I wholeheartedly agree.

[1] https://mobile.twitter.com/antirez/status/122328600521977446...

[+] core-questions|6 years ago|reply
There was never anything wrong with PHP, really.

* If you wanted to scale it horizontally, it was ready to do that 15+ years ago

* No problem running it completely stateless

* Deploys are completely sane and predictable, it's just a bunch of files, and even when composer came along it didn't really change that too much

* Performant enough as far as the interpreted web languages go

* No problem writing a RESTful backend in it and fronting completely "modern" client facing tech on the top if you want

* Server side rendering since day 1

Like, it came down to people complaining about some function names / param orders as if it were the end of the world. I think a certain subset of people (shall we call them hipsters?) are just keen on finding new ground where they can rewrite the same boring things instead of working hard to improve the ecosystem of something existing.

I moved on from PHP aeons ago because it got this undeserved bad rap, but I still follow it and would welcome the chance to run it again.

[+] mhd|6 years ago|reply
I would say that e.g. the current Rails stack actually is quite complicated, but that's because the current web stack is a horrible mess and Rails does the brave attempt of managing all, from providing images to delivering JS packages to friggin' websockets.

This isn't contrasting Ruby to PHP, this is contrasting the web that was with the web that is.

And actually, even when Rails was founded the PHP stack was inadequate for this -- which is why current practice includes all the parts that antirez is complaining about? Gems? PHP has composer, barely any serious project doesn't use it. Rack? Granted, once the PHP server is setup you don't have to account for an abstraction layer. Rakefiles? I don't think there's a standard task runner for PHP, but e.g. Laravel has envoy and I would assume that almost any project needs some kind of shim there, even if it's just shell scripts. YAML? Well, erm, ok, I won't defend that…

The times where PHP means directly accessing a `.php` file for every "page" have passed by. If you look for simplicity there, oh traveler, beware…

[+] kugelblitz|6 years ago|reply
Symfony (https://symfony.com/) and Slim (http://www.slimframework.com/) are also worth looking at. Though since Symfony has become more modularized, I think it can also be used as a micro framework.

I've also started looking at Flask and Django of Python, can't help the feeling, that the Python frameworks are a bit more mature in terms of breaking changes.

[+] neovive|6 years ago|reply
The Laravel ecosystem (framework + libraries) is a very productive and developer-friendly stack. Documentation and training resources are ample and the community is generally very open and patient to both new and experienced developers. If you're already comfortable with PHP or just want to try something new, definitely consider Laravel/PHP as an option. You might still opt for Node, Ruby, etc., but I wouldn't simply disregard Laravel/PHP for historical reasons.
[+] Cthulhu_|6 years ago|reply
I've recently moved back to PHP; stuck on a php 5 version, but I was surprised at how fast I was back into it.

It has a heap of problems due to mistakes made in the past and - perhaps more worrying - a LOT of misinformation posted on the internet. Then there's the trope of PHP developers always building their own frameworks and CMSes and the like.

And I'm dealing with a big legacy codebase where the original author did not understand separation of concerns (or sql injection for that matter), with constructs like a switch returning a different SQL query depending on a string value, globals to store the result in (which is concatenated XML transformed to JSON at the bottom of the 5000 line file, which in turn includes thousands of lines of additional code). And the project was started in 2012, when modern PHP and frameworks were already a thing.

I'm doing new work in more neatly organized classes at least.

[+] fs2|6 years ago|reply
This is pretty awesome, I've been migrating from C# and NodeJS back to PHP and it's awesome. Want to know why?

- Everything is either built-in or can be enabled from an OFFICIAL repository (like functions for bc,xml,etc). No more trusting sketchy npm packages or having to pull in a ton of dependencies that might stop working some day.

- It's so fast and elegant to consume a (SOAP or REST) webservice. Visual Studio insists on creating tons of files, obscure web.config settings and other misc. stuff. PHP handles this in a couple of lines.

- Development feels natural, every file can be a single class if you want and there are plenty of highly matured frameworks available.

I estimate I've slashed development time in half compared to C#, less bugs and less security issues (verified through two independent code auditors). Even large projects are easier to work on in PHP compared to C#

[+] pathartl|6 years ago|reply
I have to disagree with pretty much everything you've written, because it seems like you're running into issues of a paradigm shift.

If I'm going to consume a web service, I am going to write the models in C# and let a JSON deserializer like Newtonsoft.JSON map everything. To me, there's nothing better than having a fully modeled web service. I learn a bit about how the service works when writing the models. I know what the data looks like before I start working with it in my own application.

Regarding your web.config note, I guess I don't understand what you're trying to get at. .NET projects tend to throw configuration items into, well, a configuration file. Again to me this is far superior to doing the PHP-industry-standard of having a config.php and chucking a bunch of global variables into it. Putting configuration items behind a parser in a document that you expect the user to edit is good practice.

Development feels natural, every file can be a single class if you want and there are plenty of highly matured frameworks available.

Maybe this is a note more for the NodeJS space, but a single file per class is the general guideline for C#/.NET. Additionally, I've generally found that the .NET framework and libraries written against it tend to be of much higher quality, are more secure, and are more production ready than most I've worked with in PHP land.

On top of that, Visual Studio is a wonderful IDE and is pretty much the gold standard of our industry. I've not had a better experience as a developer than being able to create a .NET Core MVC web application and hit the ground running. I've written anything from 5 line Azure Functions to working with 100k+ line web applications and I'm not sure I could have done it without the excellent debugger available and the very context-aware Intellisense typeahead. In contrast, other than PhpStorm, I find PHP environments to be extremely messy and a bit of a hack to get working properly. If I didn't have some sysadmin background I'm not sure I'd move outside of "debugging" using var_dump().

I was a PHP dev primarily from ~2009-2017 and have been working almost exclusively in C# since.

[+] pbowyer|6 years ago|reply
> [PHP is] so fast and elegant to consume a (SOAP or REST) webservice.

I would never choose PHP to consume a SOAP webservice if I could use C# or Java instead. And I say that as someone who's been consuming SOAP with PHP since 2001, from travel industry suppliers, major CRMs/ERPs and a bunch of quirky services.

PHP's SOAP library just isn't very good. From what I recall it doesn't support some of the security extensions natively, struggles with namespacing, has small changes to data structures when serializing/deserializing (I recall attributes/values being a pain to setup) and worked with some endpoints but not others. That could be the endpoints' fault, but when Microsoft is producting it - I sure expect the endpoint to work with PHP's bundled SOAP library.

Multiple times I fell back to constructing the XML myself (sometimes with the DOM builder, other times with handcrafted XML strings that were tested in SOAP-UI until they worked and given placeholders for data.

Last week I had to investigate ow a service had got the wrong data, and neded to load the XML response again to see the data in our app. The PHP XML extensions give a different structure to the SOAP extension; to get back the result you have to mock the response in a subclass of SoapClient, feed in your XML and let the extension parse it. That works, and is elegant in a way - but it could be so much better.

Rant over ;)

[+] mharroun|6 years ago|reply
Honestly php seems like the common cold... an annoyance that is everywhere and treated with little seriousness. However every evolution it gets better and stronger and adapts other learnings from other languages. It really shouldnt be treated as a joke any more.

Ps: I love php and jquery... not for any real saas systems but no other tool set allows me to spin up and prototype full web app prototypes in sub 90 min. As a senior tech manager php and Jquery allow me to show functional prototypes quickly and easily get buy in from other department stake holders.

[+] elric|6 years ago|reply
PHP hasn't been a joke since PHP 4, when it pretty much supplanted Perl, which until then had been the dominant scripting language for the web. Its deceptive simplicity has been both its strongest and weakest point. On the one hand, it helped draw hordes of young developers into the field. On the other hand, it gave a lot of programming power to a bunch of people with very little programming experience, leading to the image of a buggy joke of a language.

I don't think who has had a serious look at PHP would call it a joke these days.

[+] monoideism|6 years ago|reply
> As a senior tech manager php and Jquery allow me to show functional prototypes quickly and easily get buy in from other department stake holders

I totally get it if you prefer to leverage your knowledge of jQuery, but modern JavaScript is just as quick to use. Eg, `fetch`, `querySelector`, and many more. Combined with modern css with flexbox and grid, and prototyping becomes very quick.

[+] irrational|6 years ago|reply
One of the biggest complaints I've read about PHP is that many things are not consistently named (having never used PHP, I might be wrong). If this is true, are there any plans to fix this?
[+] pjmlp|6 years ago|reply
PHP 5 was what made me make peace with PHP.
[+] krsdcbl|6 years ago|reply
It never should have, the treatment php gets mostly feels like people finding it "not cool enough", seldomly I've seen someone have a real reason to avoid it
[+] esistgut|6 years ago|reply
Every time I see an article about new features in PHP I search the page for the "annotation" keyword. To be honest I find it a little bit puzzling that to this day a large part of the ecosystem (Symfony, Doctrine, API Platform) revolves around docblock annotations.
[+] piinbinary|6 years ago|reply
Given how much PHP is used, having a JIT will probably save a meaningful amount of electricity
[+] thdrdt|6 years ago|reply
PHP7 already dropped the load on a lot of servers. It was amazing to see that systems like WordPress became twice! as fast by just switching PHP version.
[+] agumonkey|6 years ago|reply
I'm not sure if I'm inventing things but I think there was a report when facebook introduced hiphop compiler.
[+] kyriakos|6 years ago|reply
The main benefit will be for long running php processes rather than stateless web requests. It does open php as an option for other applications which are currently being implemented with nodejs and python.
[+] gcpwnd|6 years ago|reply
The JIT won't be a game changer, at least initially.
[+] blibble|6 years ago|reply
that page seems to state that it only works in the context of a single request

unless you've got CPU bound PHP code... it seems like a complete waste of effort

[+] chx|6 years ago|reply
> Undefined variable: Error exception instead of notice

Well, this is where the chaff separates from the wheat. There's no small amount of crappy code out there which will WSOD after this. Or actually print the exception because they couldn't even bother to switch display errors on... Of course, no even remotely sane codebase will be affected, but... Make no mistake, this is a good change but it will cause some teeth gnashing.

[+] codetrotter|6 years ago|reply
Over time I think (hope) this sort of change will help to improve the code that people write.

But I will not be surprised to see some people say things like “PHP 8 broke my code”. Of course, what those people might not realize is that PHP 8 did not break their code, the code was always broken, and PHP 8 is now going to surface the brokenness of that code.

But even with code that people refuse to fix, this sort of change will make the brokenness of that code more apparent to others, and so the number of people that use that broken code will cease to grow. If not entirely, then at least reduce in pace of growth.

That is good for the ecosystem of computing. As a proponent of correctness in computing, this makes me happy :)

We all write bugs, but everything our tools and languages of choice can do to help us reduce the number of bugs and the severity (impact on security) of our bugs, the better.

[+] tim--|6 years ago|reply
PHP has always warned about this since version 5.6 - if not earlier.

To stop the warnings, configuration would need to be changed in PHP config, or those warnings be silenced by the developer.

Any decent webapp has had this issues resolved a long time ago.

I would suggest that websites that will be effected probably will not migrate to PHP 8 that quickly.

[+] blowski|6 years ago|reply
In my experience, the kind of crappy codebase this would affect would never be upgraded anyway. Many of them are still on PHP 4!
[+] webkike|6 years ago|reply
If you only get this error after installing Sys packages, it is time to upgrade
[+] cdubzzz|6 years ago|reply
> The @ operator no longer silences fatal errors

Interesting. There are still some legitimate (well, “legitimate”) use cases for that behavior e.g. with PHP’s native XML extensions.

[+] treve|6 years ago|reply
Are you sure those are _fatal_ errors?
[+] agentultra|6 years ago|reply
Union types!

This is amazing to see. So many languages these days agree that functions are good. Now they're all adding type systems of one sort or another.

PHP has always been a bit behind the curve but good on the developers for pulling in a cool feature like this.

[+] tylerjwilk00|6 years ago|reply
# Summary of some of the new changes:

## Union types

Specify multiple types

    public function foo(Foo|Bar $input): int|float;
## JIT

Just in time compiler for improved performance

## Static return type

Return static of class

    class Foo
    {
        public function test(): static
        {
            return new static();
        }
    }

## Weak maps

Prevent blocking of garbage collection for improved memory usage when needed

    private WeakMap $cache;

## ::class on objects

Get class type from object like get_class($object)

    $foo = new Foo();
    var_dump($foo::class);

## fdiv function

When you don't care about division by zero

    fdiv($x,0);

## Concatenation precedence

Math takes precedence in string concatenation.

    // this
    echo "sum: " . $a + $b;
    // evaluated as this
    echo "sum: " . ($a + $b);

## Some others

- Create DateTime objects from interface

- Type annotations for internal functions

- Variable syntax tweaks

- Breaking changes

- Consistent type errors

- Reclassified engine warnings

- Reflection method signature changes

* Note: HN pretty please get improved mark down parsing

[+] guggle|6 years ago|reply
I've used PHP from 1998 to 2016.

Things I remember I didn't like about/around PHP:

- too many aspects of the language were dependent on config/php.ini.

- it had errors and exceptions. I just wanted exceptions.

- was not very interesting/useful/great outside web backend.

- mb_* functions were not enabled by default

- it had no decent REPL.

- "reference" libraries had bad APIs or were over-engineered.

I'm not sure about the state of these issues now, but frankly I never felt the need to look back. Good to hear there's still progress though.

[+] Annatar|6 years ago|reply
I expect to have some time soon and I'm planning on writing a full-blown application in PHP, using nothing but functional style programming. Should be fun.
[+] fraktl|6 years ago|reply
Judging by comments I saw and what I had my own clients tell me over the phone/mail, it would appear that there's stigma associated with PHP, mostly due to one super-popular blog post called "PHP - a fractal of bad design". I won't go into rebuttal here, the author of the post did enough damage as it is.

PHP evolved significantly since version 4. Version 5 was the "big" deal, with good object oriented features. Version 7 brought the performance in, so we could get rid of Facebook's crappy HHVM (thank you PHP team). Version 8 brings JIT, however most of the workload isn't CPU bound but I/O bound.

So, here's something for PHP devs:

Swoole. http://www.swoole.co.uk -> this is an extension for PHP which brings in the same primitives available to people using Node.js or Golang - coroutines, async I/O, channels, event loop control and much more.

What it essentially does is turn ALL I/O from synchronous to asynchronous. Without any code change or control structure in form of async/await or promises. Write synchronous code, get asynchronous performance.

From my own experience (I've been running swoole in production for 18 months), the performance gain I saw was minimum 500% to a maximum of 2000% (the numbers aren't a joke).

As for PHP - it's a programming language. You can use it right or you can use it badly. This rule applies to almost any language. There's no language in this universe that can turn a bad programmer into semi-ok programmer or even good programmer. If you haven't got the habits and knowledge, there's no language that can rectify it. I've seen way too many people thinking the language of their choice is to blame, but it was always the person in the chair.

PHP performs well. Ecosystem is quite large and luckily there aren't competing standards. Composer, the package manager, is wonderful. There's plenty of frameworks to choose - for web and for CLI usage. Features are being added, slowly but steadily.

I use PHP with Laravel + nginx, next to Nuxt + Vuetify + TypeScript for frontend stuff. Personally, I really like how the mentioned tech can be utilized to create great apps fast - with structured code, that look good and work quick.

Edit: one of the best and most powerful features in PHP (starting with 7.4) is the FFI - foreign function interface. The option to utilize libraries or entire software, without the need to write PHP extensions, is what's amazing for me (I also need it due to nature of my work).

PHP is way more powerful than people give it credit for. But I guess that's what happens when opinions are formed by looking at titles and number of "likes" or other meaningless numbers designed to mislead.

[+] CraftThatBlock|6 years ago|reply
I'm a bit confused. I thought PHP 7 introduced a JIT, hence why it was much faster (in some cases ~5x faster). How is it different from the PHP 8 JIT?

I always assumed that HHVM is what brought JITs to PHP originally, followed by PHP itself.

[+] rnijveld|6 years ago|reply
PHP 7.0 was mainly faster because the internal variable data structure (zval) was redefined such that PHP doesn't need to follow so many layers of indirection and doesn't need a full ref-counted heap allocated data structure for every int and bool in your script.
[+] jonny383|6 years ago|reply
I believe there were attempts at implementing JIT in PHP 7 which were unsuccessful against the timeline for release. Instead, they did other optimizations and managed to squeeze quite a bit of performance doing this (comparable to HHVM).
[+] lowercased|6 years ago|reply
at least some of the speed bump in 7 came from reduced memory usage. IIRC, array pointer size was reduced significantly - something like 120+ bytes per array entry was reduced to ~40 bytes, so far less memory needed to be allocated and managed throughout an execution cycle. I'm sure there were other reasons for speed boosts, but that is one that's stuck in my head for some time.
[+] CiPHPerCoder|6 years ago|reply
PHP 7 didn't introduce a JIT. There was an experiment in the 7.x series, but it never surfaced.
[+] no_wizard|6 years ago|reply
I like that 8 has some great changes coming and the JIT will be a long term win.

I just hope the core maintainers evaluate true async/await constructs for PHP. I also hope that the JIT leads to more significant advancement in PHP and how it manages memory. For all it’s improvements it’s still really prone to memory leaks easily

[+] kingdomcome50|6 years ago|reply
I'm going to go ahead and play devil's advocate here and make the argument that iteratively transforming PHP into a Java/C# clone is actually doing a disservice to PHP. The reason PHP is so popular, and it's greatest strength, is that it offers a "simpler" paradigm of development.

Many of the latest RFCs accepted (while I agree are great steps forward for the language) may actually reduce it's foothold going forward. That is, they are not a good fit for the community. I see no compelling reason to choose PHP for a greenfield project if, when used in a production environment with a stable framework, you are writing essentially the same code as you would for Java/C#. There is hardly a feature where an ASP.NET core C# project isn't still miles ahead of the same Symphony/Laravel back-end. Hell, with the new Razor-Pages template, you are essentially writing "PHP" in C#... where you get all of the bells, whistles, helpers, type-checking, generics, pattern matching, LINQ etc that C# already offers!

IMO (emphasis on the "O") they are missing the point. I don't want my PHP application to "look" just like a Java/C# app. I don't want a `Controllers` directory and `RepositoryInterface`s everywhere... I don't want all of the same ceremony it takes to develop a .NET Core/Spring app copied into PHP. What I want is a composition of "scripts" (functions)!

PHP should focus on and develop towards it's strengths not it's weaknesses. Lean in to include. Lean in to $GLOBALS. Lean in to a more functional approach. These are the things that have made PHP so dead-simple/approachable over the years.

You want more features? Fine. Add pre-processing directives (akin to .razor). Allow for files to truly be treated as modules. Simplify/abstract templating into the language better. That is, instead of focusing on the kinds of "features" that better-enable OOP (and move away from a composition of "scripts"), focus on making it easier/better to compose "scripts". Make _that_ safer, clearer, more ergonomic. There are _plenty_ of ways to dramatically improve PHP (as a platform) without simply updating the language semantics. The language was _never_ the draw!

As many of the comments in this thread indicate/imply, PHP isn't chosen because it is such a great language, rather, it is chosen because it offers an extremely convenient development paradigm. PHP is very-much "batteries included" when compared to its contemporaries[0]. _This_ is why people reach for it over and over again. So instead of changing the vehicle (PHP), how about we give it more/better batteries instead?

/devil's advocate

How'd I do?

[0] I have always found the whole "framework vs raw PHP" debate in the community a bit humorous. The "framework" crowd never seems to really understand that, in many ways, raw PHP is a framework. What other scripting languages automatically parse HTTP requests for you as part of the runtime? Or come with a default "routing" scheme? Or offer built-in templating semantics? PHP gives you all three out of the box.

[+] jonny383|6 years ago|reply
Union types look somewhat handy, especially if you're using

    T|null
In PHP 7, you can still do

    function foo(string $bar = null): void
Which is a little clunky...
[+] EspadaV9|6 years ago|reply
In PHP 7 the correct code should be

    function foo(?string $bar): void
Having `= null` marks the parameter as optional with the default being `null`. Using `?string` means there is no default and you can pass in either a string or null.
[+] flir|6 years ago|reply
I'd rather have overloaded function signatures, to be honest.

    function add(string $a, string$b){}
    function add(int $a, int $b){}
[+] perceptronas|6 years ago|reply
Is it just me or PHP is trying to become Java? I remember 7~ years ago PHP devs were "mocking" Java and not it kinda feels like its moving there
[+] amai|6 years ago|reply
PHP and Perl are as dead as the Diesel engine in 2020. Somehow they are still everywhere, but it doesn't feel right to start anything new with them.
[+] marcrosoft|6 years ago|reply
PHP is looking a lot like Java these days.