LoginSignup
6
5

More than 5 years have passed since last update.

名前空間の下で変数を使って動的にクラス名を指定するには修飾が必要

Last updated at Posted at 2016-02-10

検証環境

  • PHP 5.5.30
  • PHP 5.6.16
  • PHP 7.0.3
<?php
namespace ns1;

class Foo
{
    public static function bar()
    {
        return __METHOD__;
    }
}

namespace ns2;

use ns1\Foo;

echo Foo::bar() . "\n"; // -> ns1\Foo::bar

//非修飾(エラーになる)
$className = 'Foo';
$className::bar() . "\n"; // -> Fatal error: Class 'Foo' not found

//修飾
$querifiedName = 'ns1\\' . $className;
echo $querifiedName::bar() . "\n"; // -> ns1\Foo::bar

//完全修飾
$fullyQuerifiedName = '\\ns1\\' . $className;
echo $fullyQuerifiedName::bar() . "\n"; // -> ns1\Foo::bar
6
5
1

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
6
5