PHP: 2006年6月アーカイブ

以下のようにすれば、クラスを定義した後でも、インスタンス変数にアクセスするメソッド(のようなもの)を動的に生成できる。
無名関数のスコープが生成時のスコープに依存しないため、引数に&$thisを与えるのがポイント。

  class Foo {
      var $str;
      function setStr($str) { $this->str = $str; }
      function doAnonFunc($argsdef, $code, $arg) {
          $func = create_function($argsdef, $code);
          return $func(&$this, $arg);
      }
  
  }
  
  $obj = new Foo;
  $obj->setStr('baz');
  
  echo 'STEP0:'.$obj->str."\n";
  echo 'STEP1:'.$obj->doAnonFunc('&$this, $str', '$this->setStr($str); return $this->str;', 'test')."\n";
  echo 'STEP2:'.$obj->str."\n";

出力:

  STEP0:baz
  STEP1:test
  STEP2:test

2009年11月

1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30          

ウェブページ

Profile

name: Michiya Honda
nick: PIA
birth: 21-Nov-1975
e-mail: pia at this domain
SNS: mixi, nowa
起業・独立サポート「katana」

2006年7月: 月別アーカイブ

このアーカイブについて

このページには、2006年6月以降に書かれたブログ記事のうちPHPカテゴリに属しているものが含まれています。

次のアーカイブはPHP: 2006年7月です。

最近のコンテンツはインデックスページで見られます。過去に書かれたものはアーカイブのページで見られます。

Powered by Movable Type 4.1