2010-02-04 12 views

risposta

9

È possibile utilizzare la funzione get_defined_functions() per ottenere tutte le funzioni definite nello script corrente.

See: http://www.php.net/manual/en/function.get-defined-functions.php

Se si desidera ottenere le funzioni definite in un altro file, è possibile provare a utilizzare http://www.php.net/token_get_all come questo:

$arr = token_get_all(file_get_contents('anotherfile.php')); 

Poi è possibile scorrere per trovare i token di funzione con i simboli definito. L'elenco di token può essere trovato http://www.php.net/manual/en/tokens.php

+0

get_defined_functions() riceve tutte le mie funzioni dichiarate da tutti i file, non dal exacly un file! – zumrasha

+0

aggiornato. potresti voler usare 'token_get_all()'. Se si utilizza include e richiede, in questo file verranno definite anche le funzioni definite negli altri file. – mauris

14

È possibile ottenere un elenco di funzioni attualmente definita utilizzando get_defined_functions():

$arr = get_defined_functions(); 
var_dump($arr['user']); 

funzioni interne sono a indice internal mentre la funzione definita dall'utente sono a indice user.

Si noti che questo genererà tutte le funzioni dichiarate precedenti a quella chiamata. Ciò significa che se si dispone di file include() con funzioni, anche quelli saranno nell'elenco. Non c'è modo di separare le funzioni per file se non assicurandosi di non avere alcun file prima della chiamata su get_defined_functions().


Se si deve avere la un elenco di funzioni per file, il seguente tenterà per recuperare un elenco di funzioni analizzando la fonte.

function get_defined_functions_in_file($file) { 
    $source = file_get_contents($file); 
    $tokens = token_get_all($source); 

    $functions = array(); 
    $nextStringIsFunc = false; 
    $inClass = false; 
    $bracesCount = 0; 

    foreach($tokens as $token) { 
     switch($token[0]) { 
      case T_CLASS: 
       $inClass = true; 
       break; 
      case T_FUNCTION: 
       if(!$inClass) $nextStringIsFunc = true; 
       break; 

      case T_STRING: 
       if($nextStringIsFunc) { 
        $nextStringIsFunc = false; 
        $functions[] = $token[1]; 
       } 
       break; 

      // Anonymous functions 
      case '(': 
      case ';': 
       $nextStringIsFunc = false; 
       break; 

      // Exclude Classes 
      case '{': 
       if($inClass) $bracesCount++; 
       break; 

      case '}': 
       if($inClass) { 
        $bracesCount--; 
        if($bracesCount === 0) $inClass = false; 
       } 
       break; 
     } 
    } 

    return $functions; 
} 

Utilizzo a proprio rischio.

+0

get_defined_functions() ottiene tutte le mie funzioni dichiarate da tutti i file, non da un solo file! – zumrasha

+0

@zumrasha: vedere la mia risposta aggiornata, che fornirà un elenco delle funzioni disponibili per file. –

+0

Chiunque usi questo potrebbe voler aggiungere 'T_CURLY_OPEN' allo switch per catturare stringhe come' "ciao {$ name}" ' – Twifty

-1

COMPRENDONO al file e provare questo:

$functions = get_defined_functions(); 
print_r($functions['user']); 
8

È possibile utilizzare get_defined_functions() prima e dopo di includere il file, e guardare a ciò che viene aggiunto alla matrice per la seconda volta. Dal momento che sembrano essere in ordine di definizione, si può semplicemente utilizzare l'indice in questo modo:

$functions = get_defined_functions(); 
    $last_index = array_pop(array_keys($functions['user'])); 
    // Include your file here. 
    $functions = get_defined_functions(); 
    $new_functions = array_slice($functions['user'], $last_index); 
+0

Uno intelligente è questo! – pie6k

+0

hai salvato le mie ore joachim – tatskie

1

Bene per quale motivo se avete bisogno di fare questo vi mostro: lima

Esempio: funzioni.php (ho appena scritto un po 'di merda casuale non lo fa Mather funziona con tutto)

<?php 

    // gewoon een ander php script. door het gebruiken van meerdere includes kun je gemakkelijk samen aan één app werken 

    function johannes($fnaam, $mode, $array){ 

     switch ($mode) { 
      case 0: 
       echo " 
         <center> 
         <br><br><br><br><br> 
          he johannes!<br><br> 

          klik hier voor random text:<br> 
          <input type='submit' value='superknop' id='btn' action='randomding' level='0' loadloc='randomshit' /> 
          <p id='randomshit'></p> 
         </center> 
        "; 
       break; 
      case 1: 
       echo "bouw formulier"; 
       break; 
      case 2: 
       echo "verwerk formulier"; 
       break; 
      default: 
       echo "[Error: geen mode gedefinieerd voor functie '$fnaam'!]"; 
     } 
    } 

    function randomding($fnaam, $mode, $array){ 

     $randomar = array('He pipo wat mot je!','bhebhehehehe bheeeee. rara wie ben ik?','poep meloen!','He johannes, wat doeeeeee je? <input type="text" name="doen" class="deze" placeholder="Wat doe je?" /> <input type="button" value="vertellen!" id="btn" action="watdoetjho" level="0" loadloc="hierzo" kinderen="deze"> <p id="hierzo"></p>','knopje de popje opje mopje','abcdefghijklmnopqrstuvwxyz, doe ook nog mee','Appien is een **p!!!!!! hahhahah<br><br><br><br> hahaha','Ik weet eiegelijk niks meer te verzinnen','echt ik weet nu niks meer','nou oke dan[[][(!*([email protected]#&*$*^éäåðßð','he kijk een microboat: <br> <img src="https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcS_n8FH6xzf24kEc31liZF6ULHCn2IINFurlFZ_G0f0_F4sLTi74w" alt="microboat" />'); 

     $tellen = count($randomar); 
     $tellen--; 

     $rand = rand(0, $tellen); 

     echo $randomar[$rand]; 
    } 

    function watdoetjho($fnaam, $mode, $array){ 

     $dit = $array['doen']; 
     echo "Johannes is: $dit"; 

    } 

?> 

Abbiamo 3 funzioni qui dentro:

  1. Johannes
  2. randomding
  3. watdoetjho

Ma chiamiamo anche queste funzioni:

  1. conteggio
  2. rand

Se usiamo get_defined_functions avremo tutte le funzioni all'interno ambito di script. Sì, le funzioni PHP sono separate da quelle dichiarate dall'utente, ma vogliamo comunque da un file specifico.

Se usiamo token_get_all riceveremo una grande quantità di dati che dobbiamo separare per primi.

Ho trovato questi numeri che abbiamo bisogno di fare alcune connessioni all'interno della matrice per abbinare le funzioni dell'utente. Altrimenti avremo una lista che includerà tutte le funzioni PHP che sono chiamate su.

I numeri sono:

  • 334 (elenco di tutte l'utente funzioni dichiarate)
  • 307 (Elenco di tutti i nomi di funzione)

Se filtriamo l'array di prendere tutto 334 elementi che hanno questo:

334 - | - funzione - | - 5

Ma abbiamo bisogno del nome della funzione e tutti gli elementi dell'array sono in relazione con il terzo valore. Così ora abbiamo bisogno di filtrare tutti gli elementi dell'array strega corrisponde al valore 3rth (5) e il numero costante 307.

Questo ci darà qualcosa di simile:

307 - | - Johannes - | - 5

Ora in PHP sarà simile a questa:

<?php 
    error_reporting(E_ALL^E_NOTICE); // Or we get these undefined index errors otherwise use other method to search array 

    // Get the file and get all PHP language tokens out of it 
    $arr = token_get_all(file_get_contents('Functions.php')); 

    //var_dump($arr); // Take a look if you want 

    //The array where we will store our functions 
    $functions = array(); 

    // loop trough 
    foreach($arr as $key => $value){ 

      //filter all user declared functions 
     if($value[0] == 334){ 
        //Take a look for debug sake 
      //echo $value[0] .' -|- '. $value[1] . ' -|- ' . $value[2] . '<br>'; 

        //store third value to get relation 
        $chekid = $value[2]; 
     } 

      //now list functions user declared (note: The last chek is to ensure we only get the first peace of information about the function witch is the function name, else we also list other function header information like preset values) 
     if($value[2] == $chekid && $value[0] == 307 && $value[2] != $old){ 

        // just to see what happens 
        echo $value[0] .' -|- '. $value[1] . ' -|- ' . $value[2] . '<br>'; 
        $functions[] = $value[1]; 
        $old = $chekid; 
     } 
    } 
?> 

risultato in questo caso è:

307 -|- johannes -|- 5 
307 -|- randomding -|- 31 
307 -|- watdoetjho -|- 43 
0

Ho scritto questa piccola funzione per restituire le funzioni in un file.

https://gist.github.com/tonylegrone/8742453

restituisce un semplice array di tutti i nomi delle funzioni.Se si sta chiamando nel file particolare che si desidera eseguire la scansione, si può semplicemente utilizzare il seguente:

$functions = get_functions_in_file(__FILE__);

1

Se non siete preoccupati per la cattura alcuni tra quelli commentata, questo potrebbe essere il modo più semplice :

preg_match_all('/function (\w+)/', file_get_contents(__FILE__), $m); 
var_dump($m[1]); 
0

ho risolto questo problema con array_diff

$funcs = get_defined_functions()["user"]; 

require_once 'myFileWithNewFunctions.php'; // define function testFunc() {} here 

var_dump(array_values(array_diff(get_defined_functions()["user"], $funcs))) 
// output: array[ 0 => "test_func"] 

Aggiornamento

per ottenere il nome funzioni "reali" Try This

foreach($funcsDiff AS $newFunc) { 
    $func = new \ReflectionFunction($newFunc); 
    echo $func->getName(); // testFunc 
}