如何获取方法的代码? 我正在尝试这样的事情:
//SiteController.php
class SiteController{
public function actionIndex(){
//bla bla..
}
public function actionCustomMethod(){
if(1){
echo '1';
} else {
echo '2';
}
}
}
//i need take code of "function actionCustomMethod(){ ... }"
preg_match('/function actionCustomMethod[^}]+/i', file_get_contents('SiteController.php'), $out);
//but the preg_match returns
/*
public function actionCustomMethod(){
if(1){
echo '1';
*/
我不知道如何使用嵌套大括号获取代码。有什么想法吗?
答案 0 :(得分:0)
class SiteController{
public function actionIndex(){
//bla bla..
}
public function actionCustomMethod(){
if(1){
echo '1';
} else {
echo '2';
}
}
}
$res = new ReflectionMethod('SiteController', 'actionCustomMethod');
$start = $res->getStartLine();
$end = $res->getEndLine();
$file = $res->getFileName();
echo 'get from '.$start.' to '.$end .' from file '.$file.'<br/>';
$lines = file($file);
$fct = '';
for($i=$start;$i<$end+1;$i++)
{
$num_line = $i-1; // as 1st line is 0
$fct .= $lines[$num_line];
}
echo '<pre>';
echo $fct;