Come ottenere l'elenco di funzioni che vengono dichiarati in un file phplista Funzione del file php
risposta
È 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
È 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.
get_defined_functions() ottiene tutte le mie funzioni dichiarate da tutti i file, non da un solo file! – zumrasha
@zumrasha: vedere la mia risposta aggiornata, che fornirà un elenco delle funzioni disponibili per file. –
Chiunque usi questo potrebbe voler aggiungere 'T_CURLY_OPEN' allo switch per catturare stringhe come' "ciao {$ name}" ' – Twifty
COMPRENDONO al file e provare questo:
$functions = get_defined_functions();
print_r($functions['user']);
È 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);
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:
- Johannes
- randomding
- watdoetjho
Ma chiamiamo anche queste funzioni:
- conteggio
- 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
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__);
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]);
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
}
- 1. lista PHP tutti i file nella directory
- 2. Sostituzione del contenuto del file in PHP
- 3. lista tutte le costanti definite da un file in php
- 4. php mysqli Lista database
- 5. PHP Array nella Lista
- 6. $ _SESSION Lista in PHP
- 7. strano funzionamento del ceil() funzione (PHP)
- 8. PHP, ottenere il nome del file senza estensione di file
- 9. Costante PHP all'interno del file JS
- 10. Parametro funzione Python: tupla/lista
- 11. PHP - Converti percorso del file system nell'URL
- 12. funzione move_uploaded_file in PHP
- 13. Download del file .zip esegue un file php danneggiato
- 14. Disattivazione download del file PHP se PHP non è installato
- 15. Modifica autorizzazioni del file caricato da PHP
- 16. PHP - Rimuovi l'ultimo carattere del file
- 17. Come ottenere l'estensione del file in PHP?
- 18. Ottieni cartella principale del file corrente PHP
- 19. Sostituzione di {{string}} all'interno del file php
- 20. PHP open file excel in del browser
- 21. Lettura del file .csv in php
- 22. Come determinare l'età del file usando PHP?
- 23. Lettura del file xlsx in PHP
- 24. funzione PHP anonimo con array_walk
- 25. lista del kernel Linux.h
- 26. funzione Haskell per la lunghezza lista
- 27. Determinazione lista del gioiello di file per la specifica
- 28. PHP ha una funzione che restituisce l'estensione corretta del file, dato un tipo di contenuto valido?
- 29. Ricerca del nome file che ha chiamato la mia funzione in PHP
- 30. Ottieni nome file del file che ha eseguito PHP include
get_defined_functions() riceve tutte le mie funzioni dichiarate da tutti i file, non dal exacly un file! – zumrasha
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