8 ms·
Modern PHP features – PHP 8.0 and 8.1
- neals 4y agoI've asked this question a couple of times on stackoverflow, but it get's removed, even though it is a legitimate question to me: I have found that working in a team with php has made it, sometimes, difficult to catch bugs that a typed language would prevent at compile time. How do larger teams work with php and frameworks like Laravel and prevent errors that are related to type-checking?
- thinkindie 4y agoyou use some static analysis tools like phpstan and psalm - I personally use phpstan and it helps a lot. Obviously you must use all the type hinting where possible and use annotations where the native ours are limited
- lnxg33k1 4y agoIt depends on the team workflow, php can be very relaxed or very strict about types, to check correctness when you pick strict modes you have tools like PhpStan, but you can also verify correctness with PhpUnit
- fndex 4y agoPHP has static types.
- alexriddle 4y agoPHPstan (or Psalm) catch any type safety issues for me. I use types extensively in my PHP code.
- sroussey 4y agoUse the type checking features of the language. They may be optional, but they exist.
- amerkhalid 4y agoI have worked on a large PHP monolith with 100+ devs. We rarely had any major bugs make it to production. I think unit tests really helped there. Of course, having QA department helped a lot too but unit tests are first line of defense. And we also used all other best practices such as PSR code formatting standards, linters, code reviews, etc.
- unculture 4y agoLots of people, particularly Laravel people, are doing static analysis with tools like PHPStan or Psalm. Over time there have been more and more type-oriented features introduced to the language too. Obviously you can't catch everything, but it's a dynamic language so that's the trade off you've signed up for.
- lostfocus 4y agoBasically what everybody else said: tests and a static code analyzer.
- simion314 4y agoI used PHPDoc to document stuff, now there is native support to declare types. Then my IDE (Intelij) will highlight type related issues as errors or warnings. It will also show you lot of other errors like using the wrong parameter count, the wrong parameter types etc. With PHPDoc you can also document "magic" stuff like objects that are auto-generated from DB tables, so you get error checks and autocompletion on column names. But I work on a small team. We use PHPUnit for unit testing, but this is not related to types.
- user3939382 4y agoI'd like to combine and expand on a few answers you got. Firstly: > bugs that a typed language would prevent This sounds like you think PHP isn't typed. It is, and with 8.1 (and even more so 8.2) the type system isn't exactly Haskell (ha) but gets much stronger than it historically has been for PHP. You enable a feature called strict_types which enforces these rules. Then you have a layer of even more powerful type checking and analysis which, though not enforced at the runtime level, is picked up and validated against by your IDE's real-time (or async external) static analysis tools. This is partially in phpDoc and there are various ways to do it. Then, besides static analysis with popular tools like PHPStan or Psalm, there are nice inspection tools like EAInspections, Sonar, etc that check for hundreds of possible errors, code smells, style issues, etc. Large, professional PHP codebases are not a big wild west of implicit coerced dynamic types. For my own projects, I consider any avoidable reliance on PHP's dynamic typing a bug, i.e. casting null to bool in conditionals.
- jw1224 4y agoI wrote awful untyped PHP 5.6 code for many years, using CodeIgniter and a very basic editor. Fully embracing PHPStorm, strict_types and EAInspections completely changed me as a developer. I hated them at first, just getting in the way and annoying me… But now several years later and I fully credit them for revitalising my career and giving me a newfound love for coding.
- Ayesh 4y agoYou just keep adding types, it gets better by time. When you do add types, go with strict types (strict_types=1). Type errors pop early when there are many type enforcements. When you find parts that you can't easily type (open file handlers for example), you can create wrappers that encapsulate the handlers. Also, use phpstan/Phan or other static analyzers like others mentioned.
- efficax 4y agostatic analysis does a lot, but yes, dynamically typed languages mean runtime bugs that a compiler would catch. this is true of php, but also javascript, ruby, python, most lisps, just oodles of languages that people build huge systems with. i'd prefer evryone embraced compile time type checked languages, but here we are.
- tyingq 4y agoLots of answers on using the type support that is there, but some use of forced casting is also common, as is using === when appropriate, avoiding "if ($bool)" in favor of "if ($bool === true)" for boolean comparisons, using linters, static analyzers, and so on.
- jw1224 4y ago> using === when appropriate It’s always appropriate. A good IDE should highlight == as a warning. My code quality and programming abilities got significantly better since forcing strict types and comparisons on myself. I can’t imagine writing PHP any other way now.
- rossriley 4y agoThere are a few instances where using == is desirable, for instance it allows you to compare two instances of an object and returns true if the properties are the same. In this case === will always return false since it checks if the two instances are the same object.
- darkhorn 4y agoUse PHP 8.1 with typed properties and parameters, PHPDoc, PHP Storm with xDebug, unit tests, code review by peers, Composer, and declare(strict_types = 1);
- TheCapeGreek 4y agoOthers have explained how PHP can be statically typed. Here's how to enforce it: Set up a linting rule that every project PHP file (with some exceptions, like templating files) needs to have the `declare(strict_types=1);` directive. Then you can also have PHPCS fix it or just generally have linting checks on PRs. For large legacy apps you can still add exceptions.
- jhoelzel 4y agothe same way you check every other code that will join the system: pipelines. I know you mean: "when i hit compile i dont see the errors directly" but that can be achieved by activated the strict type setting and your screen will turn red too =) I really think that, from all the frameworks i have used, symfony actually has the most decent debugging system. it comes with tracing logging and live debugging. so pretty much everything you would get out of any other language. With xdebug and editors like phpstorm you are also able to pretty much mimic working with PHP as you would with C#. I believe there are working plugins for Visual Studio too. Just as an excourse, I have also worked with projects that compiled php to other languages too on the fly.
- mcluck 4y agoRe: your Stack Overflow woes Stack Overflow makes a lot more sense when you think of it as Wikipedia run by mathematicians rather than a forum. If your question is ambiguous or open for discussion, it's probably not a good fit for Stack Overflow. I don't spend much time on there anymore but now you know
- deleted 4y ago[deleted]
- deleted 4y ago[deleted]
- gjsman-1000 4y agoPHP is improving, slowly, but it is still way better than the PHP 5.x days. If your last memory of PHP is from 5.x, it's a very different language now - even if it still has oddities, quirks, inconsistencies, and footguns, but PHP is still not the king of footguns - C++ is. I would ask though that if any PHP developers are reading this, I would love a feature called `modern_syntax` or similar which represents a major break in backwards compatibility in exchange for modern language conventions (i.e. no `$` prefix on variables, no `;` ending lines, perhaps some renamed core functions for consistency - we can have a debate about this). Kind of like how we have `strict_types`. Or, perhaps it could be invokable on a per-file basis, by using `<?phpmodern` instead of `<?php`. Then you could have your traditional PHP framework (say, Laravel) which has years of work on it remain intact while having a modern-PHP layer of your app-specific code on top. That would help, I would argue, with killing many of the PHP-specific criticisms while allowing some degree of backwards-compatibility.
- zach_garwood 4y agoSome people absolutely LOVE their semicolons. As a fan of Python, I don't really get it. But I think you would have to pry the semicolon from some people's cold, dead hands.
- gjsman-1000 4y agoRight - I'm only throwing the idea out there of a "modern PHP" layer that breaks some old conventions for more modern ones, but it would be opt-in and not too different, so that old code doesn't run into massive compatibility issues, and so that the "modern PHP" can be gracefully added (or not added) into any application where the developer has a different programming background, so as to allow a smoother transition.
- masklinn 4y agoTBF there are languages where the semicolon have important semantics meaning. Not needing to `\` every other line is also nice. And then there's javascript, of course, eating glue in the corner as usual.
- 4y ago
- rob74 4y ago"Constructor property promotion" - so the parameters of your constructor now automatically become properties of the class? So, for saving a few keystrokes in some cases, they have introduced a feature that I imagine is extremely confusing if you're not familiar with it (parameters go in, and then nothing happens with them - whaaat)? And what if I don't want to have my constructor parameters as properties, maybe because I process them somehow in the constructor, and set some other properties instead? And a colleague of mine is a huge fan of the new "match" keyword - he's working on a sports management application, and of course he had a "Match" class, used everywhere, which he had to rename...
- asddubs 4y agothey only get promoted if you add private/public/protected before the parameter
- rob74 4y agoAh, ok, yeah, thanks, guess that makes sense :) - and may also give someone who doesn't know this feature a hint as to what's going on...
- eropple 4y agoBeyond that, this is becoming more and more common in other languages. Anyone who ever touches TypeScript will immediately recognize it, for example, or (with a bit more of a stretch) Java/C#/Kotlin/Scala data classes and records. Feature convergence is only a bad thing if you're not spending enough time in other tools to recognize them.
- thecatspaw 4y agofrom my experience from learning typescript this is really easy to pick up on your own
- naiv 4y agoThen just do it. Nobody forces you to use promoted properties
- bambam24 4y ago
- adamrezich 4y agomight as well ask this here: does anyone have any recommendations for minimalist PHP frameworks, in 2022? I have a hand-rolled PHP site that's been getting quite a bit of traffic and it needs quite a bit of internal reworking to make things more performant and such. I'm looking at evaluating Fat-Free Framework as it seems to be more or less what I'm looking for, but I haven't seen any recent opinions anywhere about it (aside from top-ten lists, which is all you can find when you search google for such opinions). all I need is routing, caching, possibly some light database abstraction, and possibly some light templating stuff (but PHP is a templating language, and that's how I'm currently using it). I don't want MVC or any of that, just the absolute basics.
- hanikesn 4y agosymfony flex
- conradfr 4y agoAnd https://symfony.com/doc/current/configuration/micro_kernel_trait.html https://symfony.com/doc/current/configuration/micro_kernel_t...
- bkanber 4y agoAnother option is Laravel Lumen
- n42 4y agoLumen is officially not recommended. If you think you need Lumen, just use Laravel and rip out the things you don’t need. It’s much easier to pare down these days than it was when Lumen was released
- ceejayoz 4y agoLumen is being deprecated due to PHP and Laravel performance improvements that make it largely irrelevant. https://lumen.laravel.com/docs/9.x https://lumen.laravel.com/docs/9.x > Note: In the years since releasing Lumen, PHP has made a variety of wonderful performance improvements. For this reason, along with the availability of Laravel Octane, we no longer recommend that you begin new projects with Lumen. Instead, we recommend always beginning new projects with Laravel.
- mekster 4y ago"None capturing catch blocks" Since when do you not need the actual error object in the catch clause? The example is one of a bad habit of making debugging hard by not telling what exactly happened. Maybe it timed out, maybe the connection was refused, or maybe it returned 404 but I guess the author doesn't care what the detail is making it harder to reach the source of the problem. Not sure how this feature made its way in.
- ramesh31 4y agoThis happens all the time. You're doing something risky, which has no consequence to the rest of the system if it fails. Sure you could catch it and log it out, but why?
- tyingq 4y agoAlso, often you don't need more info. Like in some contexts, dividebyzero...you have all you need.
- nobleach 4y agoJavaScript did that too in the last couple of years. It's thoroughly confusing that we'd want to catch an exception and toss away all knowledge of WHAT exception was thrown. Unless one really just wants to log, "bad things happened".
- mfonda 4y agoThis information is often communicated by the type of the exception itself. Maybe it timed out: TimeoutException. Maybe the connection was refused: ConnectionRefusedException. Maybe it returned 404: NotFoundException. Depending on the specifics of how it's handled, you may or may not need the actual error message. For example, in production you may want to implement some sort of logic (retry, display friendly error message, etc.), none of which needs the actual error message. This feature isn't unique to PHP. Other languages with Exceptions, for example C# and C++, have this exact same feature.
- ryangittins 4y ago> Not sure how this feature made its way in. It's possible the language was just following usage rather than leading it. Regardless of whether or not it's right, I commonly see something like } catch (\Exception $e) { // no-op }
- mekster 4y agoPHP is getting good, sometimes I feel better than Typescript even. You can't do named parameters in Typescript unless you put every parameter as a dictionary and destructure it at the method. I just want array of class type hinting or else every return value returning an array of a class is treated as an array of mixed values unless you complement it with PHPdoc.
- ramesh31 4y ago>PHP is getting good, sometimes I feel better than Typescript even. PHP is good, and has been for years. The Zend VM is probably top 3 in the world next to JVM and V8. Incredibly more performant than Ruby or Python. The bad rap that PHP got in the early days is from all the pre-7.0 spaghetti code that was written. It’s a solid choice nowadays.
- gremlinsinc 4y agoimho, as someone who was almost a Ruby on Rails dev, because of gems, and the ease of adding packages. When laravel hit, and composer got popular that was a moot point, and php being more widely used on shared servers which was more popular w/ small clients for being 'cheap', I went w/ laravel and honestly laravel feels way more polished... For example even now with Rails you need to role your own authentication system (95% of the time that's devise) and a lot of other things baked into Laravel you need to figure out on your own, and I think they've switched asset provisioning/build systems a bunch of times, laravel has a few but each one sunset the previous mostly, except mix and vite are kinda still both in production, vite I think will probably become the defacto before long in most new projects. PHP is beautiful since 7.0, and keeps getting better. Before 7 and Before composer it was just a hackety POS, and didn't look appetizing at all, there's definitely sexier languages/frameworks out there that have 10x the reqs/second than php can get, but there's costs w/ that - and that's usually length, and time to market.
- deleted 4y ago[deleted]
- nesarkvechnep 4y ago
- dang 4y agoRelated: Choosing PHP in 2022 and beyond - https://news.ycombinator.com/item?id=32280057 https://news.ycombinator.com/item?id=32280057 - July 2022 (80 comments) Whats New in PHP 8.2 - https://news.ycombinator.com/item?id=31153698 https://news.ycombinator.com/item?id=31153698 - April 2022 (136 comments) Modern PHP - https://news.ycombinator.com/item?id=30786927 https://news.ycombinator.com/item?id=30786927 - March 2022 (263 comments) PHP – The Right Way - https://news.ycombinator.com/item?id=30219984 https://news.ycombinator.com/item?id=30219984 - Feb 2022 (332 comments) PHP in 2022 - https://news.ycombinator.com/item?id=29889705 https://news.ycombinator.com/item?id=29889705 - Jan 2022 (306 comments) Others?
- Minor49er 4y agoThe Match Expression feature is interesting. According to the PHP docs, it can even handle non-identity expression, although the approach seems a little hacky: https://www.php.net/manual/en/control-structures.match.php#example-137 https://www.php.net/manual/en/control-structures.match.php#e... <?php $age = 23; $result = match (true) { $age >= 65 => 'senior', $age >= 25 => 'adult', $age >= 18 => 'young adult', default => 'kid', }; The above example will output: string(11) "young adult"
- ryangittins 4y agoI've seen the same hack done with `switch (true)` in pre-PHP8 code (and other languages) as well.
- gremlinsinc 4y agomatch is basically a cleaner, more succinct switch, I hardly ever used switches before, though I use match a LOT. switch ($i) { case 0: echo "i equals 0"; break; case 1: echo "i equals 1"; break; case 2: echo "i equals 2"; break; } verses: $output = match($i) { 0 => 'i equals 0', 1 => 'i equals 1', 2 => 'i equals 2', default => 'i is unknown' } echo $output; the result is basically the same, but match is more of an enclosed switch that just returns instead of does side effects, then you can do what you like w/ that. Ymmv, but match is a great code saver, and is very nice for enums and methods on enums. Before match i'd probably do something like: $output = 'i is unknown'; if($i == 0){ return 'i equals 0'; } if($i == 1) { return 'i equals 1'; } if ($i == 2) { return 'i equals 2'; } return $output; Not really, I'd probably do.. if($i) { return "i equals {$i}"; } return 'i is unknown'; but the point was if I had to check for multiples to match something, then do something else, that's how I would do it... albeit this is a simple case with a better solution.
- jw1224 4y agoI use `match` like this a lot now, often with PHP 8.1's enums[1]. It makes it easy to write clean dynamic accessors, without all the extra blocks required with multiple `if` branches: /** Check the status of this Task instance. */ public function status(): Status { return match (true) { $this->inProgress() || $this->isInReview() => Status::Started, $this->isApproved() || $this->isRejected() => Status::Finished, default => Status::Planned, }; } [1] https://stitcher.io/blog/php-enums https://stitcher.io/blog/php-enums
- otar 4y agoPHP is awesome. I’ve been using it since my early career and didn’t switch to other stack… it’s been evolving like a crazy lately. The only thing I miss in the language right now is generics. PHP is not your ugly language any more, quite some time to be honest…
- lampshades 4y agoWhy do you need generics? It’s dynamically typed.
- lampshades 4y agoSometimes all I want to do in life is build some sort of community website with PHP. I might even upload it through SFTP the first version. Maybe when I retire and don’t care about employability anymore I’ll be able to make that dream a reality.