PHPのスクリプトでは、先頭にdeclare,namespace,useなど複数の定義を書く必要がある場合があります。
これらの定義を複数書く場合、どの順番で書くのが正しいでしょうか?
PSR-2とその後継であるPSR-12に準拠させると、以下の順番で書くのが正しいです。
<?php
declare(strict_types=1);
namespace App\Controllers;
use \App\Model\UserModel;
use \App\Contollers\BaseController;
use function \App\Util\{functionA, functionB, functionC};
use function \App\Util2\function D;
use const \App\Util\{CONSTANT_A, CONSTANT_B, CONSTANT_C};
use const \App\Util2\CONSTANT_D;
class UserController extends BaseController
{
...
}
上記の書き方の、元になるPSR規格
上記の書き方は、PSR-2, PSR-12の下記の規約がもとになっています。
[PSR-12]
ファイルの先頭は、下記の順番で書く必要がある
File-level docblock.
"<?php"のdocblock
One or more declare statements.
declareの定義
The namespace declaration of the file.
namespaceの定義
One or more class-based use import statements.
classのuse定義
One or more function-based use import statements.
関数のuse定義
One or more constant-based use import statements.
定数のuse定義
The remainder of the code in the file.
残りの内容
[PSR-2]
When present, there MUST be one blank line after the namespace declaration.
namespaceを書く場合は、namespace定義の後には、1行の空白行が必要
[PSR-2]
When present, all use declarations MUST go after the namespace declaration.
use句は、namespace定義の後に書かなければならない
[PSR-2]
There MUST be one blank line after the use block.
use句の後には、1行の空白行が必要
[PSR-2]
declare(strict_types=1);を書く場合は、<?phpのすぐ下に書かねばならない(PSR-12の定義)
[PSR-12]
Declare statements MUST contain no spaces and MUST be exactly declare(strict_types=1) (with an optional semi-colon terminator).
strict_typesを書くときは、`declare(strict_types=1)`と書く必要がある。※カッコの前後に空白など入れてはいけない。また、最後にセミコロンを書いてもよいし省略してもよい
こちらもおススメ