views:

423

answers:

3

You can do this in Python, but is it possible in PHP?

>>> def a(): print 1
... 
>>> def a(): print 2
... 
>>> a()
2

e.g.:

<? function var_dump() {} ?>
Fatal error: Cannot redeclare var_dump() in /tmp/- on line 1
+3  A: 

No, it is not possible to do this as you might expect.

From the manual:

PHP does not support function overloading, nor is it possible to undefine or redefine previously-declared functions.

HOWEVER, You can use runkit_function_redefine and its cousins, but it is definitely not very elegant...

You can also use create_function to do something like this:

<?php
$func = create_function('$a,$b','return $a + $b;');
echo $func(3,5); // 8
$func = create_function('$a,$b','return $a * $b;');
echo $func(3,5); // 15
?>

As with runkit, it is not very elegant, but it gives the behavior you are looking for.

Paolo Bergantino