1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

変数名で指定したクラスのインスタンスを作る。

Posted at

変数名で指定したクラスのインスタンスを作る

ソースコード

<?php
class Cat {
    public function say() {
        echo "Nya".PHP_EOL;
    }
}

$cat1 = new Cat();
$cat1->say();

$className = 'Cat';
$cat2 = new $className;
$cat2->say();

実行すると

php new_instance_useing_value.php
Nya
Nya

説明

$className = 'Cat';
$cat2 = new $className;
$cat2->say();

変数 $className に格納された Cat クラスを生成する。

参考記事

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?