--> -->

skimemo


Laravel のバックアップ(No.2)


_ 今日のLaravel

これは、Laravelを使った開発の中で気づいた事を毎日一つメモしていくものです。


_ 2018/12/7 php5とphp7での配列を使ったメソッド呼び出しの挙動の違い

以下のコードにおいて、php5とphp7で挙動の違いがありました。

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
<?php
 
class test {
 
    public function __construct() {
        echo "test!\n";
        $method[0] = "test2";
        $this->$method[0]();
    }
 
    private function test2() {
        echo "test2\n";
    }
 
}
 
new test();
  • php5(5.6.30)の場合
    >php test.php
    test!
    test2
  • php7(7.1.24)の場合
    >php test.php
    test!
    PHP Notice:  Array to string conversion in F:\test.php on line 8
    PHP Stack trace:
    PHP   1. {main}() F:\test.php:0
    PHP   2. test->__construct() F:\test.php:17
            :
    PHP Fatal error:  Uncaught Error: Function name must be a string in F:\test.php:8
    どうやら変数が配列の場合、php7だと「$this->$method」で一旦区切って解釈するようです。

    解決方法は以下の通り。
    -	$this->$method[0]();
    +	$this->{$method[0]}();
    これでphp5でも7でも動作するコードになりました。