20 ms·
Modern PHP
- makeitdouble 5y agoA small addition from 7.3 that was long awaited, indentation preserving heredoc/nowdoc: https://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc https://www.php.net/manual/en/language.types.string.php#lang...
- dvh 5y agoWhich linter supports these?
- nolok 5y agoLook at phpstan
- francislavoie 5y agopsalm, phpstan, and phpstorm all support all these features as a static analysis level.
- temp8964 5y agoBecause I never intentionally follow the updates of programming languages I use, I find from time to time that I am not using the new features. However, I find JetBrains IDEs can be very helpful in this regard. Its warning messages educate me to use new language features I am not aware of or I have never tried.
- lekevicius 5y agoDoes any other language require to use a special notation, similar to PHP’s “$”, any time a variable is referenced? I can only think of CSS, using “--“.
- krapp 5y agoPHP got that from Perl AFAIK. Bash does it too, and TCL.
- chubot 5y agoI'm pretty sure that historically shell is the common influence of PHP, Perl, and Tcl. PHP also inherits shell's here doc syntax, e.g. <<EOF . Not sure if Perl has that. Actually PHP started out as a bunch of cgi-bin scripts, if I recall. It was very much "a shell for the web". It kind of annoys me that they all require $ on the left, whereas shell only requires it on the right, which somehow makes more sense to me, e.g. a=$b # shell $a = $b # PHP and I think Perl
- pweezy 5y ago> It kind of annoys me that they all require $ on the left, whereas shell only requires it on the right Interesting - it makes it look like Bash uses $ to “read” from the variable, while in PHP/Perl $ only indicates that the rest of the symbol _is_ a variable.
- tyingq 5y ago>>PHP also inherits shell's here doc syntax, e.g. <<EOF . Not sure if Perl has that. It does. >>It kind of annoys me that they all require $ on the left Larry Wall says he went that direction to make namespace clashing between $dog, @dog, %dog, and "sub dog {}" (scalar, array, hashtable, function) a non-issue. http://www.wall.org/~larry/natural.html http://www.wall.org/~larry/natural.html ("Disambiguation")
- ZeroGravitas 5y agoRuby also has $ for global variables, which I assume it also got via Perl. And @ for instance variables, and @@ for class variables.
- TylerE 5y agoIt's much worse in perl, because it changes based on how you're using it. E.g. an array vs an element of an array.
- deleted 5y ago[deleted]
- ainar-g 5y agokrapp has already mentioned the Unix stuff. BASIC had a thing with a $ at the end of a string variable, iirc. Windows' CMD.EXE used %VAR% notation (and later !VAR! notation).
- toastal 5y agoThis is called a “sigil”
- todotask 5y agoIt's more than what most of us know, Rosetta Code is a good way to find. https://rosettacode.org/wiki/Variables https://rosettacode.org/wiki/Variables
- jansommer 5y agojsoniq uses the same notation https://www.jsoniq.org/ https://www.jsoniq.org/
- dylan604 5y agojquery, lodash, etc all added prefixes (or TIL: sigil) of somesort
- throw_m239339 5y ago> jquery, lodash, etc all added prefixes (or TIL: sigil) of somesort This is false they are not sigils at all. _ and $ are legal variable names in Javascript.
- nobleach 5y agojQuery's $ and lodash's _ are not prepended to a symbol to denote a variable. Both are objects actually. In the case of jQuery, $ === jQuery (the root jQuery object). The case that the parent is talking about is PHP's requirement that all variables are denoted as such `$variable_name`. (Perl and Bash also do this)
- dylan604 5y agoi forget that's what's actually being done under the hood.
- graftak 5y agoThat’s just (part of) the variable name and not really the same.
- tyingq 5y agoThese all use sigils on variables in one way or another: Unix Shells, AWK, Perl, Ruby, Tcl, Basic, PowerShell, DOS batch scripts
- icedchai 5y agoBasic uses them at the end for string variables... A$...
- Eric_WVGG 5y agoBack in the eighties, my father taught me that the “$” character in BASIC meant “string,” so when I later picked up PHP in ‘98 I mentally thought of $someVar as “string-someVar” (regardless of the actual type, which was of course no problem for PHP), kept that habit for well over a decade… I think it was partially my self-disgust over such silly and technically incorrect thinking that led me to bail for Node as soon that was a feasible alternative. The dollar sign does kinda look like a loose piece of shoestring, though
- agumonkey 5y agoI can't remember all details but in Lisp in small pieces, author describes variable handling with a table { creation, reference/access, modification, [deletion] } with each category had it's own optional syntax, many language will avoid this through context in which the symbol is, thus (+ a 1) equates (+ (deref a) 1), but he meant that it was a choice and not an obligation and some systems used $ or other syntactic constructs.
- deleted 5y ago[deleted]
- lbj 5y agoAlso a good read in the same vein: https://eev.ee/blog/2012/04/09/php-a-fractal-of-bad-design/ https://eev.ee/blog/2012/04/09/php-a-fractal-of-bad-design/
- nobleach 5y agoWhile I enjoyed that article many years ago, and even identified with those sentiments. I've kept an eye on PHP over the years. It's not that same language. Certainly PHP, like all languages are not perfect. But I gotta hand it to the team. The evolution has been awesome.
- deleted 5y ago[deleted]
- muglug 5y agoIt’s not really in the same vein, since the OP is referring to modern PHP and your article was written over a decade ago. Many of the points in the decade-old article still stand, but the ecosystem around PHP has papered over a lot of the cracks in a variety of ways.
- unfocussed_mike 5y agoIt's not just papering over cracks, though. (There's a bit of that, but they do try to avoid it) It's a slow, deliberative process to properly fix the most widely deployed server-side web programming language. It's not going to be easy, and it is being done by fairly wise heads.
- unfocussed_mike 5y agoThis is a) ten years old, b) fairly out of date, and c) much more passive-aggressive and opinionated than people sharing it seem to think it is. I mean, in the "stances", just as an example -- "a language must be concise"? Really? It must? I think this is inappropriately assertive. IMO the better JS I have seen has avoided some of the more unnecessary conciseness. And that is before we discuss the worst example of "conciseness" thinking in a generation: JSX. PHP and its community is, if you want a different opinion, more mature, more pragmatic and entirely less screwed up than Node.js, which is, to borrow the terminology, a fractal of indiscipline. PHP's developers and its wider community have gone about fixing problems while NPM just seems to create new ones. (The author of that post is in fact a Python fan, which makes it even more chucklesome when looked at over a ten-year timescale. One of the two languages managed to bring developers along for that whole decade with a campaign of carefully planned major improvements and deprecations, without causing major schisms, and it wasn't Python.)
- Moru 5y agoThe Named Parameters [0] are useful but there are editors that solves the problem in another way. Write a function with a docblock [1] on top of it and then mouse over the function call and it shows you the documentation of the function with every parameters use. Or start typing the function name and autocomplete fills in the rest with parameter names and show the docblock above. Saves my sanity many times per day. [0] https://dnlytras.com/blog/modern-php/#Named-parameters https://dnlytras.com/blog/modern-php/#Named-parameters [1] https://docs.phpdoc.org/latest/guide/guides/docblocks.html https://docs.phpdoc.org/latest/guide/guides/docblocks.html
- Beltalowda 5y agoThe obvious downside of this is that you're adding all these noisy "@param string $filename The name of the file." and "@return string The modified filename." comments. A lot of PHP projects are littered with this kind of stuff, and when there's actually some important comment it's easy to miss.
- Tijdreiziger 5y agoIsn't this a pretty generally accepted pattern? Java and Python use a similar format for their docstrings.
- Beltalowda 5y agoIt's okay-ish if you need to document that actually needs documenting, but if you use docstrings for typing/IDE assistance people will document every single thing for that, leading to useless "documentation" like in my previous comment. That said, I personally prefer just a paragraph or two of prose over "structured" formats.
- paulryanrogers 5y agoAgree, I like to see at least an example value in the Docblock
- 5y ago
- faitswulff 5y agoAside, but I hate ligatures in code. If I didn't know what they were, I would have no idea what the blog's representation of a fat arrow => or a triple equals were. As it is, I still have to translate them before I fully get it.
- unfocussed_mike 5y agoI heartily agree. Ligature fonts and the word "performant" belong in the same circular filing cabinet, marked "not as clever as it seems".
- jimmaswell 5y agoPerformant: well-performing. There's nothing wrong with the word.
- unfocussed_mike 5y agoDon't feel too bad. Everyone has to be wrong about something. Luckily for you it's something small like this ;-)
- nkozyra 5y agoWhat am I missing? https://dictionary.cambridge.org/us/dictionary/english/performant https://dictionary.cambridge.org/us/dictionary/english/perfo...
- unfocussed_mike 5y ago> What am I missing? My joke? (I always forget how HN is hostile to whimsy. Even when it is carefully signposted with an emoticon.) Just to add though: a word making its way into a dictionary is no guarantee of its usefulness, correctness or value. It only means a couple of definitions have been found in print. That's the standard by which words make it into dictionaries; there's no semantic gatekeeper.
- steve76 5y ago
- cletus 5y agoThere are a lot of great things here but PHP just needs to embrace static typing (IMHO). Take match expressions plus enums. Incredibly useful. You know what's even more useful? When it's a type error to leave out one of the values. This means when you add a new value you'll get a bunch of errors you need to fix. Technically you can get around this with a default case but I consider that an anti-pattern in most such cases. The Hack type system, particularly the ability to express nullability, is just vastly superior. Named parameters are an interesting one. The Hack equivalent is to use shapes [1]. This is slightly verbose but you can express what shape fields are required and optional. Javascript manages without named parameters using anonymous objects, which is basically the same thing. I didn't know PHP lambda expressions can't be multi-line. That seems weird. Again, Hack is simply better here allowing both this syntax and anonymous functions, all of which can be multi-line. I also find the Hack collection types (vec, keyset, dict) to be superior to PHP's array with more obvious semantics and less weird type coercion. PHP's default of maintaining insertion order is amazingly useful and I'm honestly surprised more languages don't copy this. Of course you have things like LInkedHashMap in Java but doing this out-of-the-box I tend to find more natural. Anyway, I think the hate on PHP is a trope at this point, largely outdated and just boring. Modern PHP is actually quite pleasant to develop in (IMHO). [1]: https://docs.hhvm.com/hack/built-in-types/shape https://docs.hhvm.com/hack/built-in-types/shape
- yurishimo 5y agoI don’t think we need static typing as a requirement. For folks who want to opt in, it’s probably fine. The divide could be catastrophic and for me, would be a major turn off. Look at JS and TS. Some projects go all in, but then others half ass it with `any` return types all over the place. If the JS ecosystem can come together around TS, it’s probably still a decade out until it becomes the default used everywhere. That gap creates confusion and chaos. If people want similar languages with more/less features, they can create those communities. Erlang and Elixir are good examples.
- cletus 5y agoI don't think there's an alternative to optional static type checking at this point. Like you say, there's a bunch of untyped code out there. I'd actually hate to see a JS/TS divide in PHP. The typing needs to really be a superset of existing PHP and backwards compatible. Such a typechecker should cover at least the following: 1. Point it to a codebase and spit out a bunch of errors/warnings; and 2. Run it at runtime where type checks are logged or a strict mode where they're fatal.
- yurishimo 5y agoPHP is probably the best language for server side webdev today. Still insanely easy to deploy, lots of features at the language level, and the frameworks that are available are very sophisticated. Whether you like Laravel or not, it’s influence is spreading to other frameworks within PHP and other languages. Also, Laravel has some of the best docs in OSS, period. I think WordPress is pushing other projects forward as well. The tech stack over there doesn’t move nearly as fast, but the UX is still pretty good out of the box and with the enterprise clients I work with on a daily basis, they all still love WP. Back to PHP proper for a minute, the language is fast. There are efforts being made to run PHP on Serverless infrastructure or with continuous process environments. New features are added to the language on a regular basis as evidenced by this post and others. The defacto package manager, Composer, is also world class. It’s a good time to be a PHP dev! As a final point, I’ll throw out some of my worries. I’ve been writing PHP since 2010~ as a high schooler fooling around. The “Java-fication” of PHP is real. There is a push for more types and type related features. These aren’t bad in isolation, but as they move deeper into the core of the language, there is a risk of breaking legacy apps. Historically, backwards compatibility has been excellent and allows older apps to upgrade PHP versions and take advantage of performance improvements without a rewrite. I’m not advocating keeping 100% compatibility forever, but recent versions have played more fast and loose with breaking changes. We’ve done a decent job of carrying the entire community onto new versions and that will be important for continued adoption. Take a look at the open RFCs for more details. I think there is value for pulling good ideas from other languages, but we don’t need every idea from every language. Here’s to another 20 years of PHP!
- unfocussed_mike 5y ago> The defacto package manager, Composer, is also world class. Composer suddenly got good, didn't it! Composer 1.x was one of my pain points I think. I can't think of many things that really bug me much anymore. Null coalescing operators and named parameters are the kinds of things that make me happy. I also adore Laravel (and particularly Lighthouse). But what I really like about PHP is the humility and maturity of the whole endeavour. It's really typified by Rasmus Lerdorf who openly critiques his own abilities and seeks out smart people.
- jimmaswell 5y agoThe match statement is nice, but in JS it's easy enough to just index a map. {'abc': 2, 'def': 3}[x] ?? 'default';
- unfocussed_mike 5y agoEasy to write. Less easy to read.
- fermentation 5y agoPlus you have to actually allocate and evaluate the whole map right? Like if the values are FromASlowComputation() you'd have to do something else.
- francislavoie 5y agoYou can do the same in PHP, but again, not as nice to read: ['abc' => 2, 'def' => 3][$x] ?? 'default';
- idoubtit 5y agoThe example in the article is poorly chosen, because an associative array (map) would be more suitable. What you wrote is almost the same with PHP: ['abc' => 2, 'def' => 3][$x] ?? 'default'; PHP's `match` is a kind of functional `switch`. For instance, in the following example, an associative array would induce several useless function calls, and `match` is more readable than a sequence of if+returns: return match ($key) { "id", "ID" => unique_id(), "UUID" => generate_uuid(), default => findExternalId($key), };
- jasonjei 5y agoThe only thing stopping me from using PHP is just I’ve been burned in the past by massive breaking changes going up in major and even minor versions. Granted they are major releases, but the amount of work to bring existing code up to “code” is a gargantuan amount of work. I’ve dealt with similar issues in Ruby as well as Rails, but it wasn’t too hard to fix and even older syntax is happily accepted without deprecation messages. With PHP, I’ve had to cleanup very verbose code (often from older open-source packages or software) and spent hours and hours cleaning up breaking changes.
- wink 5y agoThe PHP 4->5 migration was harsh (but that was 2008 if I am not mistaken, the big 4.4 deadline was on 2008-08-08 and I've not heard anyone curse since then.
- Minor49er 5y agoThis sounds like an issue with your upgrade process and not so much with PHP itself
- NorwegianDude 5y agoNot sure how long ago you used PHP, but backwards compatability has in my opinion been excellent for at least 15 years. A ~500k LOC PHP project has basically been effortless to keep up to date with the latest versions. From what I can remember I've only done search and replace a couple of times in that period.
- ec109685 5y agoThe backwards compatibility story has been much better lately in php, including across major versions. There were some bad practices with previous versions that had to be cleaned up, unfortunately.
- ransom1538 5y agoCompared to phython2 vs phython3? What are you comparing it to? I can run php4 apps just fine. Good luck managing a phython2 app.
- 5y ago
- teddyh 5y agoSee also: https://phptherightway.com/ https://phptherightway.com/
- skilled 5y agoCan anyone recommend books/courses that actually cover "modern" PHP?
- phil_dev 5y ago"PHP and MySQL" by Jon Duckett (Wiley, 2022) is a great introduction to server-side web development. If you are familiar with his previous books then you'll be glad to hear that he employs the same highly-visual yet comprehensive approach.
- francislavoie 5y ago"Front Line PHP: Building modern applications with PHP 8" is a pretty good book. https://front-line-php.com/ https://front-line-php.com/
- conradfr 5y agoI would suggest to go to https://symfony.com/doc/current/index.html https://symfony.com/doc/current/index.html and follow the "Get Started". Or reading their free book https://symfony.com/book https://symfony.com/book
- Cyberdog 5y agohttps://phptherightway.com https://phptherightway.com is also a very good resource.
- svnpenn 5y agoI stopped using PHP. The language itself is fine, but PHP doesn't include a package manager. People will shout "but composer!", That is not PHP. That is a third party tool. What Rust understands, what Go understands, what Ruby understands, is how important the package manager is to the language. No one is an island, and "batteries included" only gets you so far. In my mind, PHP is in line with C, with the mindset of "figure it out yourself" in regards to packaging. That's not acceptable.
- gmfawcett 5y agoNitpick, but Go the language doesn't have package management. The 'go' tool -- an implementation detail of the most popular implementation -- has features for fetching packages, etc., but the language spec does not require these features or constrain how they work.
- voidfunc 5y agoHow is it any different than Python (pip) and Java (maven, gradle)?
- svnpenn 5y ago> Java (maven, gradle)? Its not, I dont use Java either, same reason. > Python (pip) Python comes with Pip, at least the one I use anyway: https://nuget.org/packages/python https://nuget.org/packages/python
- mwcampbell 5y agoHow widely is modern PHP deployed on the super-cheap shared hosts? Being able to write robust web applications that can be deployed on any cheap shared host in the world seems like a superpower.
- francislavoie 5y agoVery widely, for things like WordPress. But shared hosting is a security nightmare. VPSes are super cheap nowadays, it's way better to go with that if you're trying to start/run a business.
- Tijdreiziger 5y agoSome hosts do per-customer containerization now. For tech businesses, I agree wrt VPSes; but for businesses that run a couple of WordPress sites and where tech isn’t a core competency, you can’t beat traditional shared hosting from an ease-of-administration perspective.
- jeroenhd 5y agoI've never seen an affordable shared host that _didn't_ offer at least PHP support. They may be a version or two behind (the cheaper they get, the further behind) and they may have some functionality disabled for security (system(), file_get_contents HTTP calls, etc.) but for about half a dollar a month you can get a reasonably competent web host with enough storage to run a blog for years. That said, if you care about performance, be wary of shared hosts. Some frameworks, like Symfony, need quite a bit of CPU and IO to build a up a cache to get acceptable execution speeds. Nothing too dramatic, but shortly after setting up a website it may be slow on shared hosts with strict CPU and memory limits.
- omnimus 5y agoI believe most common is to use VPS managed by some third party service like Laravel Forge, Ploi.io, Moss.sh, Serverpilot... It gives you more control and isolation but it's still pretty much like shared host experience and not much more expensive.
- danielovichdk 5y agoWhat is this array'ish construct ? ['title' => $title, 'description' => $description] = $post;
- deergomoo 5y agoIt assigns the values of $post[‘title’] and $post[‘description’] to the variables $title and $post, respectively.
- boredtofears 5y agoJust curious, does match expressions have any advantage over using a hash (or in PHP terms an associative array)?
- francislavoie 5y agoYeah, it's more like a switch but as an expression. Some more examples: https://php.watch/versions/8.0/match-expression https://php.watch/versions/8.0/match-expression It only executes the matching branch, ignoring the others. If you used an array/map + index, then it executes the right-arm of each of the options if they're functions for example, even if their result is thrown away.
- lastangryman 5y agoUsed PHP for many years for high volume web applications. My biggest gripe is you (at least had to) run php behind another server (nginx, Apache) which meant your "scope" is always restricted to serving the current request. If you want to do something like share some heavily read data across processes you need to then introduce memcahe/redis in to your stack, whereas in something like Go this can be done in your application code. This also means PHP is a nightmare for connection management to others resources like your database - if you autoscale your API you are in a very vulnerable place for maxing out connections on your database as every client request needs to create it's own. You can solve this with something like Envoy I think, but again it's adding more complexity to your stack, more tools to configure and deploy. This was my main issue with PHP. I found the language itself fine to be honest. Not the most elegant but hardly as bad as people make out.
- rvr_ 5y agoNext time you need to take a look at PHP, those two problems can be solved by php-apcu for caching and proxysql running side-by-side with php-fpm on each server.
- lastangryman 5y agoNice, thanks for the heads up on these.
- mhitza 5y agoWith apcu you're going to pay the cost of serializing/deserializing the data. If you dump your read heavy data into a PHP file on disk, that just has a return of your generated data, you can be benefit from having that bytecode compiled data stored in opcache for free (for the entire lifetime of the php-fpm service, or until you reach the maximum opcache allocateable memory). I think that PHP gives you a few nice utilities to handle sharing, but they are problem specific. For example you might also spawn threads within a background PHP task, and there is shared memory functionality you can use in that case as well which is going to be faster than apcu or opcache.
- 5y ago
- YATA0 5y agoUsing PHP in 2022+ should be considered a crime of negligence.
- unfocussed_mike 5y agoWhy, specifically? I mean, it has problems, sure, but all languages do. What should those negligent people use instead, particularly? What's your suggestion for an alternative system that is as deployable?
- theamk 5y agoI'd personally prohibit all PHP websites that require directories which are writeable + executable. This means basically every app which can be updated from web interface, or has plugins which can be installed from web interface -- Wordpress being a primary example. I understand that it is convenient to deploy, but a single exploited vulnerability can turn a web server into a part of botnet, forever. And this has happened, numerous times. I don't have a specific suggestion for alternate system, but it should have a very clean separation between "code" and "data", and have a very easy way to completely replace "code" part. This can be done with Docker, or deb-style installation, or just a sane design which keeps things separately. And of course you can do it with modern PHP.. it's just that language makes it so easy to do the insecure thing. "I'll just make an uploads/ right next to my index.php, so users don't have to mess with server config too much" - and bam, you have a vuln. Compare it with Golang, or Java -- you'd have to work real hard to make this kind of vulnerability there.
- unfocussed_mike 5y agoAll reasonable points. Aside from WP installs I definitely lock down PHP execution to the single entry point; it's possible to do it with WP too, there are just a few more entry points, alas.
- theamk 5y agoI am sure you do, but what about average PHP programmer? There are thousands of tutorials on the web which teach the insecure way. And even in this thread, there are many people who mention "ease of deployment" as #1 PHP advantage -- do you think they'll lock down their installs? So if starting a new project, you either have a choice of going with PHP and trying to re-educate many experienced PHP programmers that their best practices are insecure... or maybe choosing some other language, like Golang and Python, instead. Those languages are secure by default, there is no need to force people to go against the grain.
- krick 5y agoAll these features have been discussed countless times in "new release" threads and such, but I don't think I ever asked public opinion on the "spaceship" operator, so I want to raise the question this time. I always ignored it as a feature that I personally don't need, but somebody else does, so ok, whatever. You see, I actually don't think I ever used usort in about 10 years (or how long is it since anonymous functions were introduced). Instead, in all of my projects there is an implementation of https://underscorejs.org/#sortBy https://underscorejs.org/#sortBy The difference is that the callback maps the value to something that is already sortable using other native PHP functions, like an integer or a string. I find it way more intuitive than writing these function($a, $b) {/* try to remember which of [-1,0,1] it is supposed to return */} abominations. So as a solutions to remembering "which of [-1,0,1] should it be" I'd expect just natively implementing in C sane sortBy function to replace this pre-historic PHP bullshit. But whatever, it's a matter of taste… …Or so I thought until now. Now that I think about it, I see [-1,0,1] callback as something really fucked up. PHP usort (and basically all PL ordering functions I know) can order only linear sequences, i.e. it returns an ordered list. Not even a lattice. Basically this means real numbers (or, more comfortable to use in a PL: strings). And with [-1,0,1] I can define whatever the fuck I want. There's nothing to stop me from implementing "paper/scissors/rock" (or even something much more convoluted) in it, and I have no idea how usort will behave then. That doesn't sound good. So I'd like somebody to persuade me that I personally need [-1,0,1] comparison model for some use case I apparently never encountered. The only reason I can think of why [-1,0,1] might be better is performance (or RAM, actually), but I don't accept it as a valid argument: somehow even my non-optimal sortBy PHP implementation always turns out to be enough, and if I really should worry about sorting performance, PHP probably isn't the right language for my use-case anyway.
- afiori 5y agoTechnically they are equivalent, meaning that theoretically you can implement one with the other. The main advantage of sorting with [-1,0,1] is if you are sorting by multiple parameters Convoluted example: sort some cars by year then by weight except with all Toyota first In general it is easy to simulate multiple SQL `order by` clauses with [-1,0,1]. Using primitives you can map each car to something like "0t-1994y-0300kg" (remembering to left pad numbers) and sort by that. In practice they are equivalent (when used correctly) but it is easier to implement primitive sorting with [-1,0,1] than viceversa. Sometimes I wish languages would have native equality and order operators on (immutable) arrays, so that [1,1]<[1,2]<[2,0]<[2,0,-1] would work...
- poopypoopington 5y agoIsn't modern PHP just Hack?
- krapp 5y agoI wish. As far as I'm concerned, Hack was a better language and I wish it had taken off. But no. For one thing, HHVM supports XHP by default, but PHP doesn't, so you still need a separate framework with a DSL to safely handle HTML in PHP. Hack also had async/await, type checking and generics. Also PHP's Composer no longer supports Hack. Hack was supposed to get its own package manager but AFAIK that never materialized.
- mekster 5y agoWith PHP 8.1 I can easily map database JSON column as an array in a model class by setting the property type as array and the database abstraction runs json_decode on array typed properties when fetching and json_encode when saving. Quite handy.
- kingdomcome50 5y agoI've probably written some version of this comment over dozen times throughout the years when discussion about PHP rears its head (note that I'm fond of PHP): PHP as a language is... okay. It's been modernized to include many of the faculties a developer would expect of a language in 2022. But honestly, I'm ready for the "improvements" to the language to stop. The closer you get to C# or Java the more obvious it is that PHP will never catch up! It's not that it has to catch up, rather, that few people actually choose PHP because the language is so great. If you were choosing a your stack based on "which language offers us the most features or highest ability to express our problem" you wouldn't be choosing PHP! Here's the secret: PHP is probably the best language for server side webdev because of the runtime! It's so dead simple to develop and deploy PHP. I mean the language itself is basically a web framework right? How many other languages automatically parse an HTTP request and hand it to you by default? Or offer built-in templating semantics for composing HTML? Or have request routing by default? I don't know of another one. That's why I, and many others, choose PHP! You know what I'd like to see? The trajectory of PHP's development change to lean in to the above -- to focus development on improving the reasons why it is chosen in the first place! I don't need a C# with slightly different syntax (or named parameters). I'd like: - Improved templating semantics - A better module system - A way to bake routing into each file (overwriting the default semantics) - Adding a built-in service-locator pattern/DI - A way to make PHP scripts more testable What I'm saying is just make it a better framework by default. I know I know... "Laravel this, Symfony that, have you heard of Slim?". Yes... I get it. There are community-made solutions to the above problems. And you know what? They won't be as performant or integrated as if the runtime itself was upgraded to make them obsolete. It's not like routing and DI are that complicated (the two most obvious reasons frameworks are employed). I like that I can write a simple API in PHP without pulling in a single dependency! It makes so many things easier (the right things too). Now let's just extend that to all of the basic facets a modern web framework offers!
- kiwidrew 5y agoI used to look down on PHP, but after being forced to use it for a while I begrudgingly came to admire it for all the reasons that you've pointed out. And I started using PHP by choice, generally for writing small scripts (no frameworks or libraries) that I could "deploy" simply by copying the .php file into /var/www. It's a very productive language when used as intended. PHP scripts on shared webhosting was the original "serverless" and you didn't have to be too careful about object lifetimes and leaking database connections because as soon as the request was finished the entire process was nuked from orbit. But "modern PHP" is the complete antithesis of everything that I grew to admire about PHP because it's just another Java or C# with awful syntax and weird equality rules and gigantic frameworks with thousands of classes and interfaces. I would very much like to see a version of PHP that dropped all the nasty namespace and object-oriented misfeatures and just focused on cleaning up the language semantics and enhancing the built-in framework features...
- briandilley 5y agoand it kicked and screamed the entire time
- 65 5y agoOne day I hope PHP will come up with a more user friendly template literal system. I love the javascript template literal system since single quotes and double quotes are all fine, and you can add variables, ternaries, and even functions inside of your template literal. With PHP there's no one great way to write templates, there's all just kinda clunky ways (e.g. heredoc or using double quote strings with variables inside).
- dot_michael 5y agoI still have to type $ whenever I use a variable. No thanks.
- francislavoie 5y agoYou also need to do that if you ever write bash scripts. That such a weird thing to get hung up on. You'll get over it after a week of working in PHP.
- ihateolives 5y agoNot if you use IDE that takes care of it. Intellij IDEA or PhpStorm just let you type the variable and put $ there for you.
- theonething 5y agofrom https://phptherightway.com/#errors https://phptherightway.com/#errors : $ php -a php > echo $foo; Notice: Undefined variable: foo in php shell code on line 1 > This is only a notice error, and PHP will happily carry on. This can be confusing for those coming from “exception-heavy” languages, because referencing a missing variable in Python for example will throw an exception: > The only real difference is that Python will freak out over any small thing, so that developers can be super sure any potential issue or edge-case is caught, whereas PHP will keep on processing unless something extreme happens, at which point it will throw an error and report it. This is the kind of mentality that scares me about PHP. The author is saying that an undefined variable is just a small thing, nothing to be worried about and the correct behavior is not to "freak out" about it and just carry on. And only stop if something "extreme" happens. Am I crazy to think that this is crazy? I can't think of a case where continuing with program execution after referencing an undefined variable is a good thing. Trying to use an undefined variable is a bug, a potentially very serious one, so I prefer my language to stop me from writing this bug, not just "note" it.
- matyasrichter 5y agoExcuse me, WHAT? Every time a PHP post makes it to the HN frontpage, there's a ton of people saying how easy it is to pick up, build a project on, and deploy. I sometimes wondered "hm, maybe I was wrong about it, I might try it out". I had no idea it had skeletons like this hidden in the closet.
- dbbk 5y agoWith each major version they are bumping a lot of things up to exceptions though, to give people time to migrate.
- dormento 5y agoI thought about not responding to avert judgement, but how is this not ok for 99% of all websites? Where an "undefined variable" is very much a "small thing"? I mean, we have ways to catch those errors, its just that when they do appear in prod its usually because the project is so low impact (99%) that the budget for testing and whatnot is nonexistant (and the reasons for that vary from project to project, of course). My experience suggests that, were this error to appear in a more complex component (say a shopping cart or notification system) these "non-entirely static-content-based" parts usually are either separate projects or have their own adequately-sized test code. "But this is not a website, its a complex web app" - then PHP was probably not the most sound technical choice from the start. "But this teaches bad practices" - practices are always evolving, new languages appear from time to time. I'd rather work on fixing real world problems. "But PHP is old!" - so is Java... besides, another name for "old technology" is "stable tecnology". In short, it is best if there are no errors in your code (haha yeah right..). If there are any, and its a website written in PHP acessing an undefined variable, it is probably a small thing. And if its critical that it does not happen, its usually an engineering blunder. Not the language's fault.