Sarfraz
Sarfraz

Reputation: 382696

PHP: Get PHP's variables, functions, constants from a php file

Is there a way to get user-defined php functions, variables, constants from a php file? Following functions are not the best way to do so because they get all decalred functions/vars/constants (with hundreds of php's built-in constants and internal php functions):

get_defined_vars  
get_defined_functions  
get_defined_constants  

Suppose i have this file myfile.php:

<?php
$title = 'Sample Application';
$copyright = 'Copyright &copy; 2009';
    $my_array = array('sarfraz', 'ahmed', 'chandio');

define ('_CASTE', 'chandio');
define ('_COUNTRY', 'Pakistan');


function add($val1, $val2)
{
    return ($val1 + $val2);
}

function subtract($val1, $val2)
{
    return ($val1 - $val2);
}
?>

Now how can i get all variables/functions/constants from that file and probably store in an array?

Thanks

Upvotes: 2

Views: 2293

Answers (3)

Dr. DS
Dr. DS

Reputation: 1285

To get all variables defined in a file

$init_var = get_defined_vars();
include_once('file_to_check.php');
$init_var2 = get_defined_vars();
unset($init_var2['init_var']);
$variables_defined_in_file = array_diff_key($init_var2, $init_var));
var_dump($variables_defined_in_file);

you should repeat above code by replacing get_defined_vars() for

get_defined_vars()  
get_defined_functions()  
get_defined_constants()

Upvotes: 0

user187291
user187291

Reputation: 53940

call get_defined_functions, then include the file, call get_defined_functions once again and compute the difference.

Upvotes: 0

mauris
mauris

Reputation: 43619

You probably want to try the PHP Tokenizer.

http://www.php.net/manual/en/ref.tokenizer.php

From an external script:

<?php

var_dump(token_get_all(file_get_contents('myscript.php')));

?>

Upvotes: 6

Related Questions