2013-10-29 3 views
0

메소드의 코드를 얻는 방법은 무엇입니까? 나는 이런 식으로 뭔가를 시도하고있다 :클래스의 메소드 코드를 얻는 방법

//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'; 
*/ 

내가 중첩 된 중괄호와 코드를 얻을하는 방법을 모르겠어요. 어떤 아이디어?

+2

정규 표현식은 중첩 된 데이터 구조를 비교하는 데 적합하지 않습니다. 간단한 파서를 작성해야합니다. – Barmar

+0

[Reflection] (http://php.net/manual/en/book.reflection.php) –

+0

고마워, 오늘 밤해볼 게. – user2629587

답변

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; 
+0

음, 작동합니다. 그러나 ReflectionMethod를 문자열 데이터로 사용하는 방법은 무엇입니까? 이렇게 : file_get_contents ('SiteController.php')? – user2629587

+0

당신의 질문이 클래스와 속성에 관한 것이라면, ReflectionClass 문서를보고 속성 ('$ reflectionClass-> getProperties()'과 비슷하게 처리 할 것) – Asenar

+0

그런 문제를 해결했습니다. preg_match_all ('/ function [^ \ {] + \ {(. *) \}/Ux', file_get_contents ('SiteController.php'), $ matches); – user2629587

관련 문제