I have a function(this is exactly how it appears, from the top of my file):
<?php
//dirname(getcwd());
function generate_salt()
{
$salt = '';
for($i = 0; $i < 19; $i++)
{
$salt .= chr(rand(35, 126));
}
return $salt;
}
...
And for some reason, I keep getting the error:
Fatal error: Cannot redeclare
generate_salt() (previously declared
in
/Applications/MAMP/htdocs/question-air/includes/functions.php:5)
in
/Applications/MAMP/htdocs/question-air/includes/functions.php
on line 13
I cannot figure out why or how such an error could occur. Any ideas?
This errors says your function is already defined ; which can mean :
you have the same function defined in two files
or you have the same function defined in two places in the same file
or the file in which your function is defined is included two times (so, it seems the function is defined two times)
To help with the third point, a solution would be to use include_once instead of include when including your functions.php file -- so it cannot be included more than once.
Solution 1
Don't declare function inside a loop (like foreach, for, while...) ! Declare before them.
Solution 2
You should include that file (wherein that function exists) only once. So,
instead of : include ("functions.php");
use: include_once("functions.php");
Solution 3
If none of above helps, before function declaration, add a check to avoid re-declaration:
if (!function_exists('your_function_name')) {
function your_function_name() {
........
}
}
You can check first whether the name of your function exists or not before you declare the function:
if (!function_exists('generate_salt'))
{
function generate_salt()
{
........
}
}
OR you can change the name of the function to another name.
You're probably including the file functions.php more than once.
In my case it was because of function inside another function! once I moved out the function, error was gone , and everything worked as expected.
This answer explains why you shouldn't use function inside function.
This might help somebody.
I had strange behavor when my *.php.bak (which automaticly was created by notepad) was included in compilation. After I removed all *.php.bak from folder this error was gone.
Maybe this will be helpful for someone.
Another possible reason for getting that error is that your function has the same name as another PHP built-in function. For example,
function checkdate($date){
$now=strtotime(date('Y-m-d H:i:s'));
$tenYearsAgo=strtotime("-10 years", $now);
$dateToCheck=strtotime($date);
return ($tenYearsAgo > $dateToCheck) ? false : true;
}
echo checkdate('2016-05-12');
where the checkdate function already exists in PHP.
I would like to add my 2 cent experience that might be helpful for many of you.
If you declare a function inside a loop (for, foreach, while), you will face this error message.
I don't like function_exists('fun_name') because it relies on the function name being turned into a string, plus, you have to name it twice. Could easily break with refactoring.
Declare your function as a lambda expression (I haven't seen this solution mentioned):
$generate_salt = function()
{
...
};
And use thusly:
$salt = $generate_salt();
Then, at re-execution of said PHP code, the function simply overwrites the previous declaration.
I'd recommend using get_included_files - as Pascal says you're either looking at the wrong file somehow or this function is already defined in a file that's been included.
require_once is also useful if the file you're attempting to include is essential.
I had the same problem. And finally it was a double include. One include in a file named X. And another include in a file named Y. Knowing that in file Y I had include ('X')
Since the code you've provided does not explicitly include anything, either it is being incldued twice, or (if the script is the entry point for the code) there must be a auto-prepend set up in the webserver config / php.ini or alternatively you've got a really obscure extension loaded which defines the function.
means you have already created a class with same name.
For Example:
class ExampleReDeclare {}
// some code here
class ExampleReDeclare {}
That second ExampleReDeclare throw the error.
If your having a Wordpress theme problem it could be because although you have renamed the theme in your wp_options table you havn't renamed the stylesheet. I struggled with this.
I had this pop up recently where a function was being called prior to its definition in the same file, and it didnt have the returned value assigned to a variable. Adding a var for the return value to be assigned to made the error go away.
You have to deactivate the lite version in order to run the PRO version.
This errors says your function is already defined ; which can mean :
you have the same function defined in two files
or you have the same function defined in two places in the same file
or the file in which your function is defined is included two times (so, it seems the function is defined two times)
I think your facing problem at 3rd position the script including this file more than one time.So, you can solve it by using require_once instead of require or include_once instead of include for including your functions.php file -- so it cannot be included more than once.
or you can't create function in loop
such as
for($i=1; $i<5; $i++)
{
function foo()
{
echo 'something';
}
}
foo();
//It will show error regarding redeclaration
Related
I have a php class that uses "include" to load some html and php from a file. Within that file I want to access the class object that included the file, but I keep getting "Fatal error: Call to a member function makeSizesSelect() on a non-object ..."
I've tried both include and require, I've tried declaring globals, I've tried everything I can think of and everything I've so far found on SO. Nothing seems to allow the file I include to have php code access the object that included it.
Any ideas?
Here's a few snippets ...
The class file:
class cdf {
public $version = 001;
public function cdf_shortcode( $atts,$content )
{
$this->slog( 2,"shortcode() case: show" );
require( 'templates/container.php' );
}
}
And the required file container.php contains the following (amongst other stuff):
<?php
echo "version = ".$this->version;
?>
I then try to use the object:
$cdf = new cdf();
$cdf->cdf_shortcode( null, null);
The line $this->slog( 2,"shortcode() case: show" ) works. It runs that function (which I haven't included in this snippet) just fine. But then the file I require (or include) cannot use $this to access the object. I'm at a loss. :-(
All I want to do is access within the included file, the variables and methods in the class that included the file ...
Sorry, some added information. I'm not sure if this makes any difference. The code above is all part of a WordPress plugin.
Curious issue with a curious solution. I finally found the answer over here:
Possible to access $this from include()'d file in PHP class?
I tried all the obvious solutions this poster tried (globals, casting to another variable, etc) with the same lack of success. Turns out, just changing the file extension from .php to .tmpl fixed the issue, and my included file can now access the object that included it. Weird. (Of course, the downside now is that my IDE doesn't colour my code for me. :-( )
Thanks for your suggestions guys.
In the file you included you need to instantiate the class.
<?php
$yourClass = new cdf();
echo "version = ".$yourClass->version;
?>
When you want to access a function in a class, you need to instantiate the class first otherwise you wont have access to anything inside of it.
Also make sure the file you are including wont be included anywhere else where the class cdf doesn't exist because that will result in an error.
The variable $this can only access methods, variables, etc. only if they are in the same object.
Update based on your answer that seems to have worked:
Example.php
<?php
echo $this->returnString();
echo $this->randomVariable;
File.php
<?php
class IncludedClass
{
public $randomVariable = 123;
public function returnString()
{
return "some random string";
}
public function meh()
{
require_once('Example.php');
}
}
$meh = new IncludedClass();
$meh->meh();
I'm going crazy over these past few days and I really need your help because I don't know what else to do. I tried everything.
Here is the problem:
I have two files. site.php and logs.php.
Here is the content of logs.php:
class Logs {
function __construct() {
}
}
Now comes the fun part, beginning of 'site.php':
require_once("database.php");
require_once("logs.php");
class Site {
private $db;
private $logs;
function __construct() {
$this->logs = new Logs(); ### this is the error line
$this->db = new MySQLDatabase();
}
}
They are all in the same directory. Why can't it find my class?
PHP might be including the wrong the file. PHP will search the include path before looking inside the script's directory. You may somehow have a logs.php in your include path (See This PHP manual for details.) I suggest maybe adding an echo "hello world"; in the root of your logs.php.
You might also have accidentally enclosed the class inside another class or function. Make sure the class is only inside the tags.
Thank you all for helping. I have found out what the problem was! Turns out, for some reason I shouldn't name my php file 'logs.php'. As soon as I renamed it, it works perfectly. I have no idea why but it just wont work with that name.
I have a PHP script that registers approximately 20 functions. Ideally it'd be loaded with require_once. I want make it so that even if somehow it does get loaded more than once, it wouldn't try to re-register the functions. I could wrap each declaration in !function_exists, but I'm wondering if there's a faster way. (Or do you think 20 calls to !function_exists is negligible?) I tried using exit but that causes an error. Is it possible to exit w/o throwing an error ?
if ( /* already loaded */ ) {
/* leave gracefully */
}
/* declare ~20 functions */
if (!defined('ALREADY_LOADED')) {
define('ALREADY_LOADED', true);
// rest of your code goes here
}
This checks to see if a constant ALREADY_LOADED is defined, and if it is not, it defines the constant and will do whatever else you want.
After it's been run once, the constant will be defined, and it will not run a second time.
I suggest using a more descriptive constant name than ALREADY_LOADED.
I think using OOP is the most practical way
Can be used as a class with static functions
class SimleClass{
public static function func1($arg){...}
}
use it
SimpeClass::func1($arg);
or sigleton
class SimleClass{
protected static $_instance=null;
private function __construct(){...}
public static function getInstance(){
if(is_null(self::$_instance)
self::$_instance=new SimpleClass();
return self::$_instance;
}
public function func1($arg){...}
}
use it
SimpleClass::getInstance()->func1($arg);
and how to connect it think itself
can use include_once
and can implement the autoloader class
function myClassLoader($className){
include_once "/lib/$className.php";
}
spl_autoload_register(myClassLoader);
=============================================================
for more concrete answer requires more data.
Perhaps your application, you can rearrange to get the more logical structure
If you as an author don't require it more then once, (or use require_once() consistantly) there shouldn't be a problem about re-registering functions.
As for exiting without an error, try die().
I would try not to redeclare functions in first step (here require more than once).
Doing 20x function_exists() does not cost anything, only some time writing and wrapping ;)
Perhaps you could try to use classes/methods instead.
function_exists is no bad.
You can write your php script files in the following manner.
/* file1.php */
if(!defined('FILE1')) {
define('FILE1', 1);
/////////////////////////
// PUT file contents here.
/////////////////////////
}// file.php finished.
Now you can include this file as many time as you want here and there. Nothing will be redefined again.
I`m currently working on a script, and I have the following situation.
function somnicefunction()
{
require 'someexternalclass.php';
$somevar = new SomeExternalClass();
}
For some reason, the above breaks the function. I'm not sure why, I haven't seen much documentation in php.net regarding this, plus google returned no real results.
Does anyone have any idea ?
If you call the function more than once, you may encounter an error by trying to include the same file.
Try using require_once() instead. Other than that, there is nothing inherently 'illegal' about your example.
Your code is absolutely valid. I tested it on localhost and it works just fine. I used following piece of code:
function.php
function loadClass()
{
include_once "include.php";
new SomeExternalClass();
}
loadClass();
include.php
class SomeExternalClass {
public function __construct( ) {
echo "loads...";
}
}
Are you sure you don't have any typo there? If you aren't getting any error, it might indicate that you haven't used the function anywhere.
Try declaring the object first and then pass it as a parameter to the function:
require 'someexternalclass.php';
$somevar = new SomeExternalClass();
function somnicefunction(SomeExternalClass $somevar)
{
// Do function stuff
}
I am getting this error for re-declaring saveorder() however, I don't think I am?!?
Cannot redeclare saveorder() (previously declared in :10) on line 71
8.function saveOrder()
9.{
10. include 'tables.php';
11. $orderId = 0;
12. $shippingCost = 5;
...
68. }
69. echo $orderId;
70. return $orderId;
71. }
You could be including the file that contains the function more than once:
include 'file.php';
include 'file2.php';
file.php:
include 'file2.php';
Cannot redeclare saveorder() (previously declared in :10) on line 71
Either use include_once or require_once to make sure it doesn't happen (this can cause problems if you try to include it twice in two separate locations (like first in a file, then later inside a function for some reason, the second one will not work if you include the _once part).
You must be including the current file (where the lines are from) multiple times.
An easy fix is using
if (!function_exists('saveOrder')) {
function saveOrder() {...}
}
However, I recommend creating a new functions.php file, including in only once, and placing all functions there.
Either tables.php contains a function also called saveOrder(), or the file you posted actually IS tables.php. PHP can't have 2 functions with the same name in the same namespace.
this could also be caused be saveorder() being delcared inside another function that is called multiple times.
eg.
function func1()
{
function saveorder()
{
echo 'x';
}
saveorder();
}
for ($i=0;$i<2;++$i)
func1();
I think this must be a bug in PHP since where you have ":10" I get all sort of strange symbols that do not occur anywhere in my code - ie. one time it might be ":0", next time ":196870" and the next time "!qhsu89s3". I also find that if I wait around a bit before refreshing then it normally sorts itself out.
Not too encouraging I have to say, but I presume a problem with PHP on Windows.