LoginSignup
10
7

More than 5 years have passed since last update.

変数名自体を取得する

Last updated at Posted at 2017-03-21

http://qiita.com/mpyw/items/43e7d2e17f1c4507b363
http://qiita.com/khsk/items/6fbf1f5a84250ec294df
なんか目に入ったので、もっと普通にやってみた。

    /**
    * 変数名を返す
    * @param mixed 値は使わない
    * @return String @paramの変数名。直接値を入れたときはnull
    */
    function getVarName($var){
        $b = debug_backtrace(null, 1)[0];
        return preg_match(sprintf('|%s\(([^\)]+?)\)|', $b['function']), preg_replace('/[[:space:]]/', '', implode('', array_slice(file($b['file']), $b['line']-1))), $m) ? ($m[1][0]==='$' ? $m[1] : null) : null;
    }

    getVarName($hoge); // '$hoge'
    getVarName('fuga'); // null
    getVarName($this->foo); // '$this->foo'
    getVarName (
        $bar
    ) ; // 改行とか入れてもいける

どんなスコープからでも呼べる、はず。

問題点その1:1行でgetVarName()を2回呼ぶと1回目の値が返る。

    // 1回目は'$a'だが2回目も'$a'になる。
    getVarName($a);getVarName($b);

問題点その2:変数名に')'が入ってるとそこで切れる。

    getVarName(${'varN)ame'}); // '${'varN'になる
    getVarName($closure()); // '$closure('になる

その1は呼び出された行と回数を保持しておけばどうにかなるだろうけど面倒なのでやめた。
その2は正規表現をがんばればどうにかなるだろうけど面倒なのでやめた。
続き誰かよろ。

これ以上正確にしようとするなら構文解析しないと無理かな?

10
7
2

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
10
7