今晚在看Thinkphp源碼的時候,看到了標籤解析的函數。請看具體例子:
/** * switch標籤解析 * 格式: * <switch name="a.name" > * <case value="1" break="false">1</case> * <case value="2" >2</case> * <default />other * </switch> * @access public * @param string $attr 標籤屬性 * @param string $content 標籤內容 * @return string */ public function _switch($attr,$content) { $tag = $this->parseXmlAttr($attr,'switch'); $name = $tag['name']; $varArray = explode('|',$name); $name = array_shift($varArray); $name = $this->autoBuildVar($name); if(count($varArray)>0) $name = $this->tpl->parseVarFunction($name,$varArray); $parseStr = '<?php switch('.$name.'): ?>'.$content.'<?php endswitch;?>'; return $parseStr; }很明顯:這個函數返回的是一個字串。而且返回的字串都是這種格式:
<?php switch('.$name.'): ?>'.$content.'<?php endswitch;?>這種格式,如果直接echo 或print_r 輸出的話,肯定是不行的。我就在想:怎麼讓這種格式的字串起作用呢。
想了很久,終於想到一種辦法能讓那種格式的字串起作用了。用file_put_contents這個函數就可以了。
測試代碼:
<?php/**@Description:**/function echo_char(){$a = 'a';$b = 'b';$c = 'c';$echo = '<?php echo \'\$a is '.$a.' and \$b is '.$b.' \$c is '.$c.'\';?>';file_put_contents("test.php", $echo);}echo_char();?>
效果:
<?php echo '\$a is a and \$b is b \$c is c';?>
可是這時候,還有<?php ?>這個格式,用正則處理就好了。我想:在THinkphp中也是這樣做的吧。如果不對,請大神指出。。