Hatena::ブログ(Diary)

*


uyern;icay8iytmviyuriuirut958FGy8yr3nnri.nuwac(ui3
huiUIhui;uwa3hmujmv.lu1luorcmlm
iuhnN84amrom4itomv
7tbxcn

11Thu09September09012011Thu

PHP5.3 軽いおさらい

大分前に、ちょっとだけ触って満足した5.3。

今日は軽くおさらいしてみた。

主にnamespaceとクロージャ


namespace Test\Primary;

class Sandbox
{
    public $property = 'property of sandbox';
    
    public $method;
    public $methods = array();
    
    public function __construct()
    {
        $method = function($arg)
        {
            Test::printBr($arg);
        };
        
        $method('called at __construct()');
        
        $this->method     = $method;
        $this->methods[0] = $method;
        $this->methods[1] = $this->method;
    }
}

class Test
{
    public $property = 'property';

    public static $static = 'static';

    public function __construct()
    {
        Test::printBr('making instance of Test');
    }

    public function execute()
    {
        $outerLocal = 'outerLocal';
        
        $function = function($arg)
        {
            $Sandbox = new Sandbox();
            
            $local = 'local';
            
            Test::printBr($local);        // o
            Test::printBr($outerLocal);   // x
            Test::printBr(Test::$static); // o
            Test::printBr($arg);          // o
            
            //$Sandbox->method('called method from instance'); // x
            
            $Sandbox->methods[0]('called array key 0 from instance'); // o
            $Sandbox->methods[1]('called array key 1 from instance'); // o
        };
        
        $function('arg');
    }
    
    public static function printBr($str)
    {
        echo $str.'<br />';
    }
}

$Test = new Test();

$Test->execute();


namespace Test\Secondary;

class Test
{

    public function execute()
    {
        \Test\Primary\Test::printBr('called from another namespace');
        
        $Class = '\\Test\\Primary\\Test';
        
        $primaryTest = new $Class();
    }
}

$Test = new Test();

$Test->execute();

出力結果

making instance of Test
called at __construct()
local

static
arg
called array key 0 from instance
called array key 1 from instance
called from another namespace
making instance of Test

ごめん、ブラウザで出力してるから改行はbrなんだ・・・。

メソッド内のローカル変数は、そのメソッド内で作ったクロージャ内に引き継げない。

jsの感覚で書いていると痛い目を見るかも。

名前空間を跨いだクラスの指定は(勿論)出来たが、可変でも出来たのはありがたい。

又、プロパティに対してクロージャを割り当てると、現存の記法と競合する為に正しくコール出来ない。

次のバージョン以降、ここがどうなるのか見ものである。

但し配列に割り当てた場合はコールできるので、一応現状でも使いようはある。

クロージャは一応オブジェクトとしてダンプされるものの、プロパティの設定等は出来ない。

タイマー処理等、イベント系処理でお世話になるこの無名関数だけど、そもそもPHPではそういう使い方は出来ない。

(出来ないし、サーバサイドなんだから別プロセスでやらせろよ的な)

実際にどのような場面で使う事が多くなるのか、少し興味深い。

uy48iu;iloimues;ciuioiw9rmc'Uafagqyuw48ay6c;om3oq7rxo9;mcuc,amt
uihtcamxwu;ouri3ra8c4jj8amcwumafhgOujh.xroiu3mmurq3;in
uiyaltuiqymc4w8yrlcw48yamco88aywio
o;urmioeumxiysiym,xxikmg;yw8iarn4n8coayxkiy
:pio;jrgwuxrowa;i7i8xmx3qm.lu
irneuaxkuMXEKSUemA$SKc4aw8jU
kauiwxoma,zpeacexux
wuryOn8wnynynwaanwcmfg
auywenayc,a,muy
k34mmvaury
rwaome