views:

202

answers:

4

I want to be able to wrap a PHP function by another function, but leaving its original name/parameter list intact.

For instance:

function A() {
    print "inside A()\n";
}

function Wrap_A() {
    print "Calling A()\n";
    A();
    print "Finished calling A()\n";
}

// <--- Do some magic here (effectively "A = Wrap_A")

A();

Output:

Calling A()
inside A()
Finished calling A()
A: 

maybe you’re looking for call_user_func_array:

function wrapA() {
  $args = func_get_args();
  return call_user_func_array('A', $args);
}

since PHP 5.3 you could even say:

return call_user_func_array('A', func_get_args());


after you’ve edited your question i would say, no, this is not possible, but there are some ways, see this question: http://stackoverflow.com/questions/948443/how-to-implement-a-decorator-in-php

knittl
This is not at all related to what I'm looking for. I edited my question to add clarification.
Fragsworth
A: 

You can't do this with functions in PHP. In other dynamic languages, such as Perl and Ruby, you can redefine previously defined functions, but PHP throws a fatal error when you attempt to do so.

In 5.3, you can create an anonymous function and store it in a variable:

<?php
    $my_function = function($args, ...) { ... };
    $copy_of_my_function = $my_function;
    $my_function = function($arg, ...) { /* Do something with the copy */ };
?>

Alternatively, you can use the traditional decorator pattern and/or a factory and work with classes instead.

Charles
+2  A: 

Apparently runkit might help you.

Also, you can always do this the OO way. Put the original fun in a class, and the decorator into an extended class. Instantiate and go.

Zed
Thank you, `runkit` is exactly what I was looking for.
Fragsworth
A: 

May be you could use eval() for that? (www.php.net/eval)

What is the original task you want this to be for?

FractalizeR