PHP の糖衣構文

Syntactic sugar for PHP

PHP 5.6 has been around for a long time as stable. However, with the release of new PHP versions, a lot of syntactic sugar has emerged. The old, very cumbersome coding has been replaced with syntactic sugar and made simple.

What is syntactic sugar

Syntactic sugar is a style of writing introduced in programming languages ​​for ease of reading and writing. is something that can be written in -Wikipedia

::class

If you often code Laravel projects, ::class I think you'll often see it written like this:

 
<?php 'providers' => [ /* * Laravel Framework Service Providers... */ Illuminate\Auth\AuthServiceProvider :: class ,
Illuminate\Broadcasting\BroadcastServiceProvider :: class , Illuminate\Bus\BusServiceProvider :: class , Illuminate\Cache\CacheServiceProvider :: class , Illuminate\Foundation\Providers\ConsoleSupportServiceProvider :: class , Illuminate\Cookie\CookieServiceProvider :: class , ?>

From within Laravel 5.1 ::class The term is used in many places. especially app\config.php in the file, long ago string ServiceProviders written with the type currently all ::class It changed to Probably because it's better recognized by the IDE.

::class to ensure that the Full Name of the class is string You can get it by type. For example, to get the fully qualified name of the ClassName class as a string, use ClassName::class.

 
<?php
AuthServiceProvider :: class ; // => 'AuthServiceProvider' Illuminate\Auth\AuthServiceProvider :: class ; // => 'Illuminate\Auth\AuthServiceProvider' use Illuminate\Auth\AuthServiceProvider ; AuthServiceProvider :: class ; // => 'Illuminate\Auth\AuthServiceProvider' ?>

.. (splat)

This is technology "stolen" from Ruby. This one is from Ruby. Compared to Ruby, it's a little lacking, but function It is convenient to use it in

 
<?php
// Traditional: function test ( $param1 , $param2 = null , $param3 = null ) { $params = func_get_args (); var_dump ( $params ); } test ( 1 , 2 , 3 ); // prints [1,2,3] test ( 1 , 2 ); // prints [1,2] test ( 1 ); // prints [1] // now: function test ( $param1 , ... $rest ) { var_dump ( $rest ); } test ( 1 , 2 , 3 ); // $rest = [2,3]; ?>

Furthermore, there is another way of writing this.

 
<?php $rest = [ 1 , 2 , 3 , 4 ]; function add ( $param1 , $param2 , $param3 , $param4 ) { return $param1 + $param2 + $param3 + $param4 ; }
add ( ... $rest ); // 10 ?>

?: (short hand ternary)

The ternary operator is usually written like this:

 
<?php $result = $param ? $param : 'default' ; ?>

$param but null If not, $param and null If 'default' Use

But with syntactic sugar you can do the same thing.

 
<?php $result = $param ?: 'default' ; ?>

I don't have to write long source anymore.

*This article is based on the " Japanese document creation style standard rules "

*This article was written by our employee Wu Jie Lindelin.org This article was reprinted and published as a contribution article for .

1 of 3