
I know there is still a lot of hatred for PHP out there, but in my opinion with version 7 at the latest (which is already over 5 years old!), PHP evolved to a great language that is fun and even type-safe to use. Next toJust-In-Time compilation, which may give a big performance boost to PHP applications, version 8 bringsa lot of useful features.
I want to present three of them I really wish I could use in JavaScript as well. I hope that comes in handy especially for those, who didn't take a look at PHP 8 yet. Let's go!
#1 Named arguments
Let's assume, you have a functionfoo
with 6 parametersa
tof
having different default values and now you want to call that function passing the argumentfalse
for the last parameter only.
PHP 8:
foo(f:false);//-----^
#"http://www.w3.org/2000/svg" width="20px" height="20px" viewbox="0 0 24 24">
In JavaScript passing arguments to a function is solely based on the parameter position, unfortunately. I know that named arguments can be simulated by using objects and destructuring, but a native feature would be much more convenient here.
#2 Match expression
The newmatch
expression of PHP is very similar to theswitch
statement, except it is an expression and can be used to directly assign values to a variable or return values. This comes in very handy, if you have more than two possible values for assignment.
PHP 8:
$fontWeight=match($weight){100,200=>"Super Thin",300=>"Thin",400,500=>"Normal",600,700,800=>"Bold",900=>"Heavy",default=>"Not valid"};
#"Super Thin";break;case300:fontWeight="Thin";break;case400:case500:fontWeight="Normal";break;case600:case700:case800:fontWeight="Bold";break;case900:fontWeight="Heavy";break;default:fontWeight="Not valid";break;}