Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

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

クラス内のメソッドを呼ぶとき、以下の例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/ (古い)

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした