PHP Making Sense of Scripts and Legacy Code

PHP to Display Object Information like Sessions, Functions, Variables and Objects

So, there you are, you have purchased a PHP script, or you have found yourself in front of your coding editor with some foreign code and you are trying to piece it together.

For a decent working script, all the coding will have a logical way to mak things work, or it will not function properly. That does not mean it is as organized as you would like.

For example, you may have a script with various files of more than 1000 lines of code and they continue to cross reference methods, classes, and functions from various files.

But, when you have found the spot in your coding where you will want to make changes, alter variables, or work with session values, you can always use a few built in PHP functions to see what variables, functions, objects and sessions are available at the precise line of code.

Within the code block further on in the article, you can see a simple PHP page that has a session, function, class, variables and objects.

The functions below will explain what they do. You can reference the code to see what data they are grabbing.

1.

get_class_vars("GetThem")
Retrieve variables within the class.

2.

get_object_vars($objectvariables)
Retrieve the new object variables that are declared 'outside' of the class.

3.

get_defined_vars()
Retrieve defined variables in a page, but, it won't grab variables within a function unless that is where you use this function.

4.

get_defined_functions()
Retrieve the function in the file. You can view internal and user defined functions.

5.

print_r($_SESSION)
Retrieve the session variables in the page.
session_start();
$_SESSION['test'] = 'test';

function test(){
    $var_in_function = "var in function will not be a defined variable";
    return $var_in_function;
}

class GetThem
{
    public $var = 10;
}

var_dump(get_class_vars("GetThem")); //outputs array(1) { ["var"]=> int(10) }
echo "<br/><br/>";

$objectvariables = new GetThem();
$objectvariables->var = 20;

var_dump(get_object_vars($objectvariables)); //outputs array(1) { ["var"]=> int(20) }
echo "<br/><br/>";

$var_out = test();
print_r(get_defined_vars());
echo "<br/><br/>";

$functions = get_defined_functions();
print_r($functions['user']); // outputs Array ( [0] => test )

echo "<br/><br/>";
print_r($_SESSION); //outputs Array ( [test] => test )