9 ms·
Modern PHP Cheat Sheet
- gregoriol 5y agoThe choice of colors for this page makes it really difficult to read
- liam_ja 5y agoI also find the super slim scrollbar difficult to use.
- orangepanda 5y agoIs there some browser flag that disables custom scrollbars? Surely its a problem for accessibility.
- minimaul 5y agoIt is actually impossible to grab for me in Safari. I wish frontend developers would stop messing with UI :(
- Denvercoder9 5y agoThe use of ligatures in the code examples also isn't helpful for people not familiar with the syntax.
- mdp2021 5y agoYou mean '=>' becoming as if ⇒ (U+D1D2)? Yes, it gives you a moment of "Mh?!".
- cute_boi 5y agoAlso no darkmode in 2021....
- mdp2021 5y agoYou should probably edit (in this case) the 'bg-blue-300' class in your broswer's "developer's tools". Some of us edit the styles as normal practice for a large number of sites, especially after the widespresad use of thin fonts, grey text etc. Surely there will also be tools (add-ons) to replace css elements as needed per domain...
- ognarb 5y agoI like how PHP is evolving. I wouldn't say it's always a joy to use but it definitively improved a lot.
- abdusco 5y agoI really want to use PHP for one-off CGI scripts, (rsync files and done, deployed), but I really wish it had methods on primitive types. It hinders discoverability. It's annoying having to look up which function I need to use, and to find that there are many alternatives, most of which are deprecated. PHP stdlib needs an overhaul, IMO.
- jonwinstanley 5y agoWouldn't that be pretty bad for backwards compatibility?
- tored 5y agoYou can always keep the old. However I don't think it is something that will ever be done, designing a good standard library is quite difficult, especially by email and rfc. I think it is better if the community designs one that gets a lot of traction to become de facto standard. All the large frameworks already has their own standard library. With the performance improvements to PHP over the years it is no longer a detriment to performance to write a standard library in PHP. And if we can get the operator overloads rfc passed we can have userland scalar objects https://wiki.php.net/rfc/user_defined_operator_overloads https://wiki.php.net/rfc/user_defined_operator_overloads
- jspaetzel 5y agoI agree, it'd be nice if the built in was more standardized and had more features. However you do have options to choose from with php these days. Really well maintained libraries exist for basically everything you could want, often they are fast, well tested and modular. And it's nice because you can even choose the style you prefer with this. Grab the symphony string lib for instance: https://symfony.com/doc/current/components/string.html https://symfony.com/doc/current/components/string.html
- sharmin123 5y agoGuide on The Mental Health Effects Of Extramarital Affairs: https://www.hackerslist.co/guide-on-the-mental-health-effects-of-extramarital-affairs/ https://www.hackerslist.co/guide-on-the-mental-health-effect...
- superasn 5y agoI really wish Php added support for Perl's qq and q operators sometime too (1) It would really make writing scripts a lot easier and cleaner. (1) https://stackoverflow.com/a/41334570/1031454 https://stackoverflow.com/a/41334570/1031454
- syberspace 5y agoI've gotten into the habit of generally using single quoted strings (with 'around them') which alleviates most problems with escaping double quotes. And for the odd string that needs to have a single quote inside I switch back to double quoting. This approach also has the added bonus of stopping PHP from accidentally evaluating something inside the strings.
- iforgotpassword 5y agoI personally think it looks broken and wrong. For short strings I don't see the point and for multiline strings, use a heredoc.
- vessel 5y agoThe reason I never use Heredoc is because you need to abandon your indentation, otherwise your tabs/spaces get included in the string. Is there a way around that?
- deleted 5y ago[deleted]
- mrcarrot 5y agoNot since PHP 7.3![1] If you indent the closing identifier, then the corresponding indentation will be removed from the content of the heredoc string. [1]: 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...
- TrispusAttucks 5y agoI thought they fixed this with [1] Flexible Heredoc in 2017 with PHP 7.3 [1] https://wiki.php.net/rfc/flexible_heredoc_nowdoc_syntaxes https://wiki.php.net/rfc/flexible_heredoc_nowdoc_syntaxes
- deleted 5y ago[deleted]
- _xnmw 5y agoAs a solo bootstrapped founder working on PHP (Laravel) every day, I was surprised to learn a LOT from this one page. Thanks for posting.
- bennyp101 5y agoThe guys behind it work at Spatie[1] which you have probably heard of some of their packages, and Freek has a blog[2] that has a lot of PHP stuff on - lots Laravel, and lots just general new language stuff (covering PHP8 features etc) [1] https://spatie.be https://spatie.be [2] https://freek.dev https://freek.dev
- pbowyer 5y agoI'm not convinced by Enums having methods. For those of you using other languages that support this, do you find them useful?
- tyingq 5y agoBorrowed from java...
- jspaetzel 5y agoI've found a couple odd instances where it'd be nice. But also utility classes work just fine too.
- Semaphor 5y agoEnums with methods are essentially a compiler supported way of having several static readonly instances on a class with a private constructor. It’s not always useful, but it can be nice, sometimes. I’ve had a few times working with C# where I’d have liked those.
- sam_goody 5y agoThe comment on Numeric values is misleading: > Use the _ operator to format numeric values: > $price = 100_10; > // $100 and 10 cents Makes it sound like the underscore replaces the decimal, which it doesn't. The underscores are simply ignored by the PHP parser, so that 10_0.1 === 1_00.1. You could afterwards use PHP to replace the `_` with a comma for display purposes, and I assume that is what they are trying to say.
- tyingq 5y agoYeah, that's a terrible example since some places do use comma as a dollars/cents separator, and others don't. And some people use floats for currency (with the obvious caveats), and might read this as "_ is the same as a decimal point". They really should just use a simpler example, like 10_000_000 being easier to read as "10 million" than 10000000.
- dotancohen 5y ago> They really should just use a simpler example, like 10_000_000 being easier to read as "10 million" than 10000000. Declarations such as `$million = 1000 * 1000;` or `$seconds_in_day = 24 * 3600;` are very common, and in my opinion more readable than the ignored-underscore syntax.
- tyingq 5y agoPerhaps, though the underscore syntax works in Perl, Ruby, Java, etc. And the context here is how to explain it, not whether it should exist and/or be used.
- bennyp101 5y agoYea, Credo[1], one of the static analysis tools for Elixir specifies it as: Numbers can contain underscores for readability purposes. These do not affect the value of the number, but can help read large numbers more easily. 141592654 # how large is this number? 141_592_654 # ah, it's in the hundreds of millions! Like all `Readability` issues, this one is not a technical concern. But you can improve the odds of others reading and liking your code by making it easier to follow. Should make it more obvious that it is purely a readability thing, and that is obviously subjective anyway [1] https://github.com/rrrene/credo/blob/master/lib/credo/check/readability/large_numbers.ex https://github.com/rrrene/credo/blob/master/lib/credo/check/...
- deleted 5y ago[deleted]
- tlackemann 5y agoI'm using Laravel/PHP for a new project and it's been a joy. A true joy. After spending the last 6+ years writing backend services in Node, PHP feels like a breath of fresh air. No restarting the server, no compiling errors from babel/typescript wackiness, no blocking threads, server-side templates out-of-the-box, and so much more. PHP has come a really long way, I really hope to see it's resurgence some day after everyone has been burned enough from running JavaScript as their server.
- minimaul 5y agoI'm writing PHP8 with the Symfony 5.3 framework at present too, and I'm also liking it. Provides what I need to build with and otherwise stays out the way. The improvements over the lifespan of PHP7, and the new things in PHP8 make PHP such a nicer language to work with.
- tyingq 5y agoNot my cup of tea, but if you really want PHP-like with JS, EJS looks really close to "I wish server-side javascript worked like PHP": https://ejs.co/ https://ejs.co/ Just needs a FastCGI wrapper. Another "Node, but PHP like" project that compares itself to EJS and other similar things: https://github.com/Yahweasel/nodejs-server-pages#why-nodejs-server-pages https://github.com/Yahweasel/nodejs-server-pages#why-nodejs-...
- deleted 5y ago[deleted]
- osrec 5y agoIt's so nice to see a comment giving PHP the praise it deserves. Honestly, PHP is a good, if not great, language to use for building solid web apps fast. People seem to love to hate it because it's the "cool" thing to do. Yet PHP developers continue to ship things faster, while JS devs are probably still fiddling with their Node environment setup...
- hakfoo 5y ago
- damagednoob 5y agoThe evolution of PHP has shown the difference that having engaged stewards of the language can make. Saw a list of quotes[1] from Rasmus Ledorf which I think explains it's stagnation. As someone who used to sneer at the language, modern PHP doesn't look out of place among Ruby, Python, etc. https://mobile.twitter.com/woketopus/status/1447150924846313475 https://mobile.twitter.com/woketopus/status/1447150924846313...
- tyingq 5y agoI don't know how this really played out internally, but from the outside it feels like Hack/HHVM kicked the PHP core team in the gut and inspired them to improve things.
- NaN1352 5y agoGenuine question from a php hobbyist : what is the equivalent of Typescript’s ability to declare an object’s structure? It’s really weird to me, I mean don’t we do this all the time? Work with eg. an $options array/obj passedto a constructor, or say, a message decoded from JSON… I could write $name = $message[‘username’] … and there is no checks in ide or runtime, while the phpdoc will just document $message to be an object or array… what am I missing? It looks like php devs create full blown classes to represent just about every data strcuture, but what if it’s just data and you don’t need any attached logic’ Isn’t there a concise way to declare a complex type?
- Ayesh 5y agoWe do indeed create full blown classes for data objects. However, it is made easier with PHP 8.0 and 8.1 (released today). Typed properties, constructor properties, and Read-only properties can significantly reduce the code bloat. - https://php.watch/versions/8.0/constructor-property-promotion https://php.watch/versions/8.0/constructor-property-promotio... - https://php.watch/versions/8.1/readonly https://php.watch/versions/8.1/readonly
- NaN1352 5y agoCan you directly cast an object / assoc array to an instance of such a class? If I have a function that receives eg a Message, it means an instance of the class right? So somehow my assoc.array/object still needs to be instanced, and if I do just $message = new Message($theData) … it doesn’t auto assign properties right? That would be handy though still very much boilerplate. I guessthe language is just designed for how it’s been used so far, may e it will change if JIT makes php more open ended in its uses.
- tyingq 5y agoIt's not clear to me what you're looking for. But you can cast arrays to objects. And you can use type declarations as arguments for functions.
- 5y ago
- pdenton 5y agoHaving used PHP since version 4 (20 years ago), I can say with confidence that its had its peak. Everything new added since 7.4 is just fluff or bloat. Fixing long standing bugs and performance improvements is fine, of course. But everything new they introduce adds to the pile of warts that's PHP. I highly regard those that try to improve it, but with the current direction it'll remain the colloquial example of how not to design a programming language.
- wyuenho 5y agoIt wasn't designed, it was evolved. The author said as much. Evolution seldom produce clean designs.
- goalieca 5y ago> Everything new added since 7.4 is just fluff or bloat. The 7.4 did not finish the type system work. Docstrings were still needed for basic type hunting.
- mtberatwork 5y agoJIT compilation certainly isn't fluff or bloat.
- tored 5y agoFFI too
- GLGirty 5y agoI found that php8 has brought numerous features that will formalize things I am currently doing as hacks and workarounds. Exceptions as expressions--I can stop writing, `$x = $context['x'] ?? ThrowWrapper::missingValue('x');` Named Arguments -- I use a hacky diy `Reflection` heavy version of this for an RMI/dispatch where json key-vals mapped to function params. Static return type and union types -- I have been relying on PhpStorm docstring hacks for this sort of type-hinting. `readonly` will be very helpful to express performant, immutable classes. I have a number of classes that are immutable-by-convention, trusting the caller not to monkey with the internals. (The idiomatic way to do this, `$immutable->getAttr()` is too costly in tight loops compared to `$immutable->attr`) PHP still has lots of warts (function calls why you so aspensive?!?!?) but I keep being pleasantly surprised by how good of a tool it's evolving into.
- NaN1352 5y agoAs a JS dev it’s nice to see php imitate some newer js syntax like nullish coalescing, arrow function, … helps me to switch between the languages. It really needs a way to declare type of small data structures though, in a very concise way (no class boilerplate, for performance eg. going through 10000’s of entities). PS : on the other hand I’m starting to dislike how languages become "designed by committee", and lose the purity of the original design.( thinking of JS mostly here with its gazillion rfcs)
- akie 5y agoAs a very long time PHP developer I say this with love, because for PHP it's actually a blessing to be moving away from the "purity" of the original "design".
- bell-cot 5y agoPerhaps worth noting - nullish coalescing is an old feature of the Unix shell. (From a quick skim through Wikipedia, it seems to have been added to `sh` in System III - released in 1981.)
- charrondev 5y agoPHP received the null coalescing operator in PHP 7 (roughly the end of 2014) after this RFC https://wiki.php.net/rfc/isset_ternary https://wiki.php.net/rfc/isset_ternary JavaScripts nullish coalescing operator landed in chrome 80 (feb 2020) over 5 years later… more like it’s PHP syntax landing in JS land.
- deleted 5y ago[deleted]
- dekerta 5y agoI've never understood why some programmers like to use ligatures, especially on a cheat sheet like this, which will be used primarily by people who aren't familiar with the syntax. It's not 'a' ⇒ 1, it's 'a' => 1, just write it out the correct way. Why are you trying to be fancy?
- martin_a 5y agoThis is done by the used font, in the markup it's correct.
- CornCobs 5y agoLooks like iosevka to me. Lovely font EDIT: I wrongly assumed at a glance because of the shape of the $. On closer look the characters are much wider than iosevka. It's jetbrains mono
- enobrev 5y agoOverall I think this is reasonable, but the font I'm using on my ide has ligatures and I think they provide a vastly better reading experience.
- someuname 5y agoBecause you're an idiot who doesn't know how fonts work.
- mdp2021 5y agoBecause the characters '=>' have been used to simulate exactly the character '⇒' : to mean an arrow, not e.g. "equality then greater than".
- FriedrichN 5y agoMy absolute favorite thing about PHP is the arrays and the ease of working with them. Whenever I find myself working in another language dealing with loads of data I'm immediately thinking of how easy it would be to accomplish it in PHP. And I've been loving all the new additions to PHP over the last few years as well. Version 5 was rather limited but since 7 it has grown into an actual programming language for which I feel I don't have to apologize for.
- e12e 5y agoIs it really useful to have ordered map as the "only" collection type? I guess it might be Stockholm syndrome - but I'm quite comfortable with a "list/array" type (numeric keys, ordered) and a "map/hash_map" type (objects as keys). Especially give that with phps "power" you can: $array = array( 1 => "a", "1" => "b", 1.5 => "c", true => "d", ); var_dump($array); Ouputs: array(1) { [1]=> string(1) "d" } https://www.php.net/manual/en/language.types.array.php https://www.php.net/manual/en/language.types.array.php
- deleted 5y ago[deleted]
- FriedrichN 5y agoThat's indeed a case where it fails, but in all my years I have maybe ran into that problem once. But it's trivial to implement a more strict form of array if you wish. And if I remember correctly there are some standard extensions that have classes to do just that. And for the record, it's not Stockholm syndrome, I use plenty of other languages and I know the benefits and drawbacks of each of those.
- 734129837261 5y agoA Reddit post from a few years ago explains pretty well why PHP has such a terrible reputation: https://www.reddit.com/r/webdev/comments/5tqoqa/web_devs_whats_your_beef_with_php/ddodpuh/?utm_source=reddit&utm_medium=web2x&context=3 https://www.reddit.com/r/webdev/comments/5tqoqa/web_devs_wha... PHP should have chosen to undergo a rebranding a few years ago, if you ask me. The stigma it has to deal with is probably unsurmountable and will be forever. If you think PHP, you think WordPress and Joomla, and that means "hacks and vulnerabilities"... It's a good language nowadays, with quirks like any other language, but I still have one big problem with it: There are too many "PHP developers" out there, and most of them are very bad, and many of the good ones are from poor regions in the world and you can find them on Fiverr doing kick-ass work for a grand total of $50.
- rexreed 5y agoHow do you find those kickass ones on Fiverr among a sea of bad ones?
- nunodonato 5y agothe good ones are not on fiverr ;)
- rexreed 5y agoThe above comment says: "many of the good ones are from poor regions in the world and you can find them on Fiverr doing kick-ass work for a grand total of $50. " That's what I'm replying to.
- tyingq 5y agoMy personal favorite PHP wtf is this one: if (md5('240610708') == md5('QNKCDZO')) { echo "true\n"; } Though I do use php, and love many things about it.
- foldor 5y agoHaving been out of PHP for several years now, I assume that needs a === instead of ==? It's unfortunate that we have the need for a ===, but it's no different that JS in that regard.
- lolspace 5y agoWhat is modern PHP?
- purerandomness 5y agoIt commonly refers to PHP 7+ paired with clean code practices and SOLID principles. The opposite is PHP5-style code from the early 2000s, no package management, no type strictness, no object orientation, just a giant spaghetti mix of JS, HTML, SQL and PHP in a 10kloc file.
- fevangelou 5y agoDo you think spaghetti code won't come from folks who use Composer? Ha!
- fevangelou 5y agoI remember inheriting a RoR v2 based project. Ended up virtualizing the entire server to migrate the damn thing as it was a big pile of dependency mess to port to a newer server stack. On a similar situation with a PHP 4 based codebase, adapting it to work on PHP 5.6 was a few hours work. Done. No other language can beat that. And thanks to a newer (and more open minded) generation of developers, PHP has a long way to go. The launch of the PHP Foundation by Jetbrains, Automattic and others - https://blog.jetbrains.com/phpstorm/2021/11/the-php-foundation/ https://blog.jetbrains.com/phpstorm/2021/11/the-php-foundati... - is also a step towards a better future for PHP.
- karmakaze 5y agoSuper cool: > Union Types - Combine several types into one union, which means that whatever input must match one of the given types: `function find(int|string $id)` TypeScript and PHP have the distinct honor of being a popular language with ad-hoc union types (not the concrete subclass/enums that other languages seem to think are sufficient).
- hollosi 5y agoPHP's main problem is its very shallow learning curve. The 5840 built-in functions provide easy ways to get many useful things done with minimal dabbling. In other words, one can be a "scripter" instead of a "programmer", and for many projects that's 100% OK. Other languages automatically filter out "scripters" from their field by demanding a certain level of mental abstraction to produce anything moderately useful. While there is absolutely no difference between a good programmer using PHP, or a good programmer using any other language/environment, but there is a big difference between the median levels and below. This in turn lowers the reputation of the field, and it becomes uncool to put PHP on one's resume, therefore the more capable programmers propagate out to other languages, which further lowers the median, etc. This happened with Perl, too...