LoginSignup
8
5

More than 5 years have passed since last update.

PHPでnamespaceの中に関数を定義

Last updated at Posted at 2017-10-21

GuzzleHTTPのテストコードを眺めていたら、こんな書き方があるものかと感心した。

概要

PHPでは namespace の後に続く {} の中に色々書ける。知らなかった。

その仕様を把握し、使いどころを考える。

名前空間付きの関数を定義

下記の場合に使えそう。

  • 関数を書いておくだけのファイルを作りたい
  • が、グローバル空間を汚染したくないため files オートローダーは使いたくない
src/SomeProject/Functions.php
<?php

namespace SomeProject\Functions {

    function test()
    {
        return 'test';
    }

}
main.php
<?php

require(__DIR__.'/src/SomeProject/Functions.php');

use SomeProject\Functions;

echo Functions\test(); // => test

echo test(); // => Call to undefined function test()

特定の名前空間の下で共通で使える関数を定義

ある名前空間に属すクラス間で共通して使いたい関数があるとする。

この場合、静的な関数のみを持つクラスを作るより、名前空間に属する関数を作ったほうがスマートに見える。

Guzzleの例も然りで、PHPUnitの bootstrap.php で関数定義すると便利かも。

src/SomeProject/bootstrap.php
<?php

namespace SomeProject {

    function getVersion()
    {
        return '1.0.0';
    }

}
src/SomeProject/SomeClass.php
<?php

namespace SomeProject;

class SomeClass
{

    public static function someMethod()
    {
        return getVersion();
    }

}
main.php
<?php

require(__DIR__.'/src/SomeProject/bootstrap.php');
require(__DIR__.'/src/SomeProject/SomeClass.php');

echo SomeProject\SomeClass::someMethod(); // => 1.0.0

echo getVersion(); // => Call to undefined function
8
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
5