3
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.

PHP 可変関数を体験してみた

Posted at

目的

  • PHPの可変関数を体験してみたのでメモを残す

情報

  • 下記のリンク先を用いて本記事に記載の内容の動作確認を行った。

方法

  • まず通常の関数をもちいて簡単な動作を定義してみる。

  • 下記に引数1と引数2の数字を足して返す関数add()を定義する。

    <?php
    
    function add(int $num_1, int $num_2){
        return $num_1 + $num_2;
    }
    
    $returnInt = add(1, 4);
    
    printf($returnInt);
    
  • 上記を実行すると「5」が出力される。

  • 先に記載した処理を可変関数の振る舞いに習って呼び出し部分を修正してみる。

    <?php
    
    function add(int $num_1, int $num_2){
        return $num_1 + $num_2;
    }
    
    $funcName = 'add';
    $returnInt = $funcName(1, 4);
    
    printf($returnInt);
    
  • 上記を実行すると結果は変わらず「5」と出力される。

  • 可変関数とは関数名を予め変数に格納しておき$関数名を格納した変数名(引数)を実行することで関数を実行しているのと同じようにすることである。

3
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
3
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?