php5.3的here doc新特性

未来的php5.3多了许多新特性。上回pea活动,在ben那里的新特性列表里,发现一个原来忽略的。就是here doc现在可以不处理里面的字符串了。就像这样:

$code =<<<'END'
    $a = 1;
    echo “$an”;
END;
echo $code;

这样有什么好处呢?本来,php是没有block或者lambda表达式这样的东西的。create_function由于那个参数是个字符串,也不怎么好使。现在可以更方便地用here doc来实现类似的功能了。比如这个:

class ArrayList {
    private $arr;
    function __construct($arr) {
        $this->arr = $arr;
    }

    function each($call) {
        foreach ($this->arr as $item) {
            call_user_func($call, $item);
        }
    }
}

$a = new ArrayList(array(1,2,3,4,5));
$a->each(create_function(‘$item’, <<<'END'
    echo “[$item]n”;
END
));

虽然比起ruby来要丑陋多了,变量作用域也不一样。不过总算聊胜于无。

 

2 thoughts on “php5.3的here doc新特性

  1. developerworks May 27, 2008 / 3:22 pm

    it’s name is “here doc”, not “hear doc”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s