简体   繁体   中英

PHP Hook Function

Can I basically do something like:

register_function_hook('myFunctionHook');

so then when any function is run:

functionA(); //The hook runs myFunctionHook();
anoterFunction(); //The hook runs myFunctionHook();
Class::functionA(); //The hook runs myFunctionHook();

Does such a thing exist?

-- Edit --

What I want to do is to get a breakdown of durations of each function. Ie. Performance Tuning. I want to get an idea of what takes all the time without installing xDebug on my Apache server, however I don't know if it is possible.

It's possible with register_tick_function() , also check this comment on the PHP manual :

$script_stats = array();
$time = microtime(true);

function track_stats(){
    global $script_stats,$time;
    $trace = debug_backtrace();
    $exe_time = (microtime(true) - $time) * 1000;
    $func_args = implode(", ",$trace[1]["args"]);
    $script_stats[] = array(
        "current_time" => microtime(true),
        "memory" => memory_get_usage(true),
        "file" => $trace[1]["file"].': '.$trace[1]["line"],
        "function" => $trace[1]["function"].'('.$func_args.')',
        "called_by" => $trace[2]["function"].' in '.$trace[2]["file"].': '.$trace[2]["line"],
        "ns" => $exe_time
        );
    $time = microtime(true);
    }

declare(ticks = 1);
register_tick_function("track_stats");

// the rest of your project code

// output $script_stats into a html table or something

This "hooks" to everything, not just functions but I think it fits your purpose.

No, its not possible the way you like

But You can achieve something close with inheritance.

 class Vehicle {
       function __construct() {
              $this->hookFunction();
       }

       function hookFunction() {
              //
       }
 }

 class Car extends Vehicle {

 } 

 Class Toyota extends Car {

 }

 new Toyota(); // will you hook function
 // this exclude static call to member functions, or other inline functions.

What you looking for is called profiler. And PQP looks like one, which is standalone.

而不是污染代码,您应该使用真正的探查器,例如xdebug提供的探查器。

Not sure if the Topic Starter needs this anymore, but perhaps others can still benefit from this.

There is a PHP lib, written completely in PHP, that allows you to do exactly what you want.

Here's an article about how it works, including the source code: http://phpmyweb.net/2012/04/26/write-an-awesome-plugin-system-in-php/

It allows you to register a function from a class to be hooked. So it basically executes your code first, and then you determine wether you want to call the original function too after your code has been executed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM