LoginSignup
16
23

More than 5 years have passed since last update.

[PHP] 変数を用いたインスタンスの生成 ~ new $class ~

Last updated at Posted at 2016-09-06

動的なインスタンスの作成

クラス内のメソッドを呼ぶとき、以下の例1 のように書く。
例1

<?php 
class hoge
{
    function hello()
    {
        echo "hello";
    }
}

$hoge = new hoge;
$hoge->hello();
// => hello

例1 では、 new hoge と書いた。
ということで、問題。
hoge は変数にできるのだろうか?

正解は、できる。
つまり、例2 のようになる。

例2

<?php 
class hoge
{
    function hello()
    {
        echo "hello, from hoge";
    }
}

class hogehoge
{
    function hello()
    {
        echo "hello, from hogehoge";
    }
}

$class = "hoge";
$hoge = new $class;
$hoge->hello();
// => hello, from hoge

$class2 = "hogehoge";
$hogehoge = new $class2;
$hogehoge->hello();
// => hello, from hogehoge

では、クラスが複数ファイルにまたがり、namespace を使った時は?

hoge.php

<?php 
// hoge.php
namespace App;
class hoge
{
    function hello()
    {
        echo "hello, from hoge";
    }
}
?>

hogehoge.php

<?php 
// hogehoge.php
namespace App;
class hogehoge
{
    function hello()
    {
        echo "hello, from hogehoge";
    }
}
?>

main.php

<?php 
namespace App;

use App\hoge;
use App\hogehoge;

include 'hoge.php';
include 'hogehoge.php';

$class = "hoge";
$hoge = new $class;
// => エラー!!!
$hoge->hello();

と、エラーになる。
この解決策は、
main.php

<?php 
namespace App;

use App\hoge;
use App\hogehoge;

include 'hoge.php';
include 'hogehoge.php';

$class = "App\hoge";
$hoge = new $class;
$hoge->hello();

という風に、namespace も含めた文字列を $class に代入することによって解決出来る。
知ってれば当たり前だろうけど、知らなかったら困る。

参考サイト

rryu さんより教えて頂き、参考サイトを追加しました。ご指摘いただきありがとうございます!
=> http://php.net/manual/ja/language.oop5.basic.php#language.oop5.basic.new

http://php.net/manual/ja/language.namespaces.dynamic.php
http://sousaku-memo.net/php-system/1417
http://dxd8.com/archives/110/ (古い)

16
23
2

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
16
23