Haytham Elkhoja
Haytham Elkhoja

Reputation: 161

auto execute a function at the end of functions in PHP

i'm looking to call a custom error log/debug function at the end of each function.

example:

at the end of every function for debug purposes without having to call that customized function every time.

much appreciated.

Upvotes: 0

Views: 727

Answers (2)

Haytham Elkhoja
Haytham Elkhoja

Reputation: 161

after much RTM i had to use debug_backtrace(); even though it's expensive.

here's how i did it:

// debug(debug_backtrace(),$query);
// $query is optional
define('DEBUG',true);

function debug($trace,$query = null) {
    if(DEBUG) {
        $caller=array_shift($trace);
        error_log("Initiating class: " . $caller['class']);
        error_log("Calling function: " . $caller['function']);
        error_log("In file: " . $caller['file']);
        error_log("@ line: " .$caller['line']);
        if(isset($query))
        {
            error_log("Performing Query: " .$query);
        }
        error_log("---");
    }
   else
       exit();
}

and at the end of each function i add the following:

function init_userInfo($ai, $v) {
    $this->user[$ai] = $v;
    debug(debug_backtrace());
}

or if the function has an SQL query:

function insertQuery($query)
{
    mysql_query($query)
        or die("MySQL Error: " . mysql_error());
    debug(debug_backtrace(),$query);

}

the output is generally like this in the php_error.log:

[20-Oct-2010 19:02:07] Initiating class: Db
[20-Oct-2010 19:02:07] Calling function: selectQuery
[20-Oct-2010 19:02:07] In file: /Code/classes/user.class.php
[20-Oct-2010 19:02:07] @ line: 100
[20-Oct-2010 19:02:07] Performing Query: SELECT * FROM user WHERE uid=(3) LIMIT 1
[20-Oct-2010 19:02:07] ---
[20-Oct-2010 19:02:07] Initiating class: User
[20-Oct-2010 19:02:07] Calling function: htmlform_addUserInfo
[20-Oct-2010 19:02:07] In file: /Code/index.php
[20-Oct-2010 19:02:07] @ line: 6
[20-Oct-2010 19:02:07] ---

Upvotes: 1

Gordon
Gordon

Reputation: 316939

Use a Debugger/Profiler for this, e.g. use XDebug or Zend Debugger.

For a comparison of the two, see

Upvotes: 2

Related Questions