Forum Moderators: coopster

Message Too Old, No Replies

How to redeclare a function

how to avoid 'Cannot redeclare foo()'

         

guarriman

4:05 pm on Feb 14, 2007 (gmt 0)

10+ Year Member



Hi.

I want to create a program which modifies 'foo()' function if a situation happens.

I don't want to insert an 'IF' within the function, since I want not to modify the original 'functions.php' file. But if I redeclare 'foo()' I get this error message:
-------
Cannot redeclare foo() (previously declared in /home/test/functions.php)
-------

How to redeclare the function? Thank you very much.

mcibor

4:38 pm on Feb 14, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I think, that you cannot redeclare the function. However there is a workaround:

use override_function [php.net]

Hope this helps
Michal

justageek

4:59 pm on Feb 14, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Something like this will work:

if (!function_exists("stripos")) {
function stripos($str,$needle,$offset=0)
{
return strpos(strtolower($str),strtolower($needle),$offset);
}
}

JAG

mcibor

5:04 pm on Feb 14, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



justageek, it's not an answer to the question. The question was "How to redeclare a function" not how to get rid of the error message.

Regards
Michal

PS. I usually use if function_exists

justageek

6:34 pm on Feb 14, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Oops. Read it to fast.

if(id10t_error('JAG')){
break;
}

cameraman

7:20 pm on Feb 14, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Or you could use variable functions.
// foo() in functions.php
function myfoo() {
echo 'myfoo';
}
$foocall = 'foo';

if($alternate)
$foocall = 'myfoo';

$foocall();

jatar_k

7:21 pm on Feb 14, 2007 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



hehe, that's good JAG

redeclaring a function is a bit of a problem and really shouldn't be a first, or maybe even last, resort

just change the primary function and document it for upgrades, if it is in a software package that may need upgrading

your other option should be to change the return, use the function as is and deal with the returned data in a different way.

If your if is to make a single case for a specific use of the function then it goes against the whole idea of general multi use functions a bit