Php 如何在类中获取方法的代码
如何获取方法的代码? 我正在尝试这样的事情::Php 如何在类中获取方法的代码,php,preg-match,Php,Preg Match,如何获取方法的代码? 我正在尝试这样的事情:: //SiteController.php class SiteController{ public function actionIndex(){ //bla bla.. } public function actionCustomMethod(){ if(1){ echo '1'; } else { echo '2'; } } } //
//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';
*/
我不知道如何获得带有嵌套大括号的代码。有什么想法吗?class SiteController{
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;
公共职能行动索引(){
//等等。。
}
公共函数actionCustomMethod(){
如果(1){
回声“1”;
}否则{
回声“2”;
}
}
}
$res=新的ReflectionMethod('SiteController','actionCustomMethod');
$start=$res->getstartine();
$end=$res->getEndLine();
$file=$res->getFileName();
回显“从“.$start.”获取到“.$end.”从文件“.$file.”获取。
;
$lines=文件($file);
$fct='';
对于($i=$start;$iRegular表达式不适合匹配嵌套数据结构。您需要编写一个简单的解析器。谢谢,我今晚会尝试。顺便说一句,这是非常糟糕的编码样式。您应该避免这种情况。我不明白什么是糟糕的编码样式。很好,它可以工作。但是如何对字符串数据使用ReflectionMethod?比如:file\u get\u contents('SiteController.php')?如果您的问题是关于类和属性的,您可以查看ReflectionClass文档并以类似的方式处理属性($ReflectionClass->getProperties()
及类似内容)。我这样解决了问题。preg\u match\u all('/function[^\{]+\{(.*)}/Ux',file\u get\u contents('SiteController.php'),$matches);或preg_match_all('/function[^\{]+\{(.*)\}/Uxs',file_get_contents('SiteController.php'),$matches);如果你想检查代码的安全性,你不能相信这个正则表达式:如果你想检查的php文件是由用户发送的,他可以发送他想要的任何东西(包括方法中的函数,或者使用巧妙的{
/})
)