PHP Tricks

PHP Tricks: Multi-value match()

Submitted by Larry on 19 April 2022 - 11:41am

Last time, I talked about fun uses of the match() expression in PHP, using unconventional types of expressions on the right-arm branch. This time, I want to expand that discussion to include fun tricks on the left-side of the =>, and how you can easily match by multiple values at the same time.

I'm going to assume you have read the previous installment about how match() works and what an "expression" means. Also, I don't claim to be the original source of these tricks. I'm just documenting them because they're cool. Let's dive in.

PHP Tricks: Uncommon match() expressions

Submitted by Larry on 15 April 2022 - 1:15pm

Recently, I've been helping a new developer out in a chat room. He's still learning PHP and working through tutorials, with lots of questions along the way. Earlier this week, by accident, he stumbled across a use of match() statements I'd not considered before. While technically not right for his use case, it did suggest another, potentially valid use for match() I'd not seen. Let's add it to the list of cool things you can do with match().

PHP Tricks: Access control bypass

Submitted by Larry on 16 March 2022 - 1:15pm

This is old-hat to some people, but it's still a nice trick.

PHP has long supported Java-esque property and method access control. Object properties and methods may be marked public, protected, or private to control what other code may access them. The general recommendation for years is that properties should be non-public in almost all cases, unless you're using the new readonly flag in PHP 8.1.

(There's a good case to be made that object-level encapsulation is the wrong model in the first place, and package-level visibility is the superior model. I happen to agree with that argument, but that's neither here nor there for the time being.)