LoginSignup
1
0

More than 3 years have passed since last update.

phpの可変関数をメソッドの中で呼び出すと未定義と怒られてしまう場合

Last updated at Posted at 2019-09-19

環境

php7

プログラム

これは、未定義とエラーが出てしまう。
関数はちゃんと定義してるし、メソッド内からの関数呼び出しなので$thisも
つけているのに。。。

hoge.php
$doProcess = "getData";
$this->doProcess();


function getData(){
  echo "データなんてないんだよなぁ";
}

さすがにミスの仕方がひどすぎて草生えない。
次に、エラーが出なくなるプログラム。
クラスの関数を呼び出す際は「->」の後は「💲」はつけないが、
今回は可変関数ということで文字列から関数を呼び出す感じになるので、
「->」のあとに「💲」をつけることで、その文字列が認識されて、うまく呼び出せる

hoge.php
$doProcess = "getData";
$this->$doProcess(); 

function getData(){
  echo "データなんてないんだよなぁ";
}

結果

ふぅ〜!呼び出せた!

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