Duplicate function
First, I did my resarch about that. But I couldn't find any solution for that. Here what I want to do. I have multiple files with the same function name, during my test I didn't specify that function and kept it simple.
The mulitple files will be included, but since the function already been declared, I'm getting that Fatal error cannot redeclare function ..., previously declared in ...
I know how to avoid that fatal error but since I include multiple files with the same function it don't fix it.
My question, is it logical, or should I rethink and do someting diffrent.
My friend told me that could 开发者_StackOverflow中文版be handled with objects and so on.
thanks for any suggestion.
Are the functions identical? In that case, you may be able to "hack" around the problem by wrapping the function declarations with a function_exists()
clause, see How to avoid fatal error Cannot redeclare function in PHP:
<?php
if (!function_exists('utility')) {
function utility() {
// ...
}
}
?>
Alternatively, it might be worth your time to read up on namespaces:
In the PHP world, namespaces are designed to solve two problems that authors of libraries and applications encounter when creating re-usable code elements such as classes or functions:
- Name collisions between code you create, and internal PHP classes/functions/constants or third-party classes/functions/constants.
- Ability to alias (or shorten) Extra_Long_Names designed to alleviate the first problem, improving readability of source code. (source)
If your functions have the same name then they should do the same thing. If they don't then you should rename them to reflect what it is that they do. That way you can include all your functions once (at the start of your script) and use them wherever you have to.
I wouldn't recommend using objects solely as a means to solving this problem (though I would recommend using them for a host of other reasons).
So to answer part of your question
My question, is it logical, or should I rethink and do someting diffrent.
Yes you should do something different, even if it means namespacing your functions (put the area of concern followed by an underscore for example)
function user_rename(){
}
function category_rename(){
}
function group_rename(){
}
// A.php
Class A {
static function myFunc(){
.................
}
}
// B.php
Class B {
static function myFunc(){
.................
}
}
// C.php
Class C {
static function myFunc(){
.................
}
}
// foo.php
include_once('A.php');
include_once('B.php');
include_once('C.php');
A::myFunc();
B::myFunc();
C::myFunc();
I think you said it "...or should I rethink and do someting diffrent."
It doesn't has to be a object. But why not outsourcing all common function in one file (i.e. common.php
) and include it from all other files with require_once 'common.php'
?
精彩评论