How to disable a function while running script in php [duplicate] - php

This question already has answers here:
Is it possible to overwrite a function in PHP
(10 answers)
Closed 9 years ago.
I have a main php file in the root which is included by several others on different directories ,I don't want to allow few functions written in main files to execute if included by another file.
I ran an test code and tried overwriting an function by re-declaring it on including but it returned an error:
a.php
<?php
function show(){echo "a";}//This is what I want to over-ride with
include 'b.php';
b.php
<?php
function show(){echo "b";}//This is the function i want to restrict.
show();
Fatal error: Cannot redeclare abc() (previously declared in C:\xampp\htdocs\abc.php:3) in C:\xampp\htdocs\xyz.php on line xx.

You can do this with anonymous functions (PHP5.3)
$show = function(){
echo "a";
};
$show = function(){
echo "b";
};
$show();
Will now echo "b".

You can't redeclare a function. You need to use unique names for each function.
The functions won't execute just because you include the file they're in. That is unless you're actively calling them inside the file.
I'd suggest evaluating the way you include files to resolve your issue. You may also want to look into include_once / require_once and the function_exists conditional.
E.g.
if ( ! function_exists( 'my_function' ) ) :
function my_function() {
}
endif;

The best way to do this would be to use PHP's OOP features, which allow you to specify visibility of methods.

You can check within a function if the "main file" is included or not, try something like this:
function someFunction() {
if (basename(__FILE__) == basename($_SERVER['SCRIPT_FILENAME'])) {
echo "Not included.";
} else {
echo "Included. No access.";
}
}
Or place the condition "outside" the function(s) definition, so it won't be defined if you include that file.
But I would go with an OOP approach.

Related

Where is the mistake in the instance? [duplicate]

This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Closed 5 years ago.
Before I ask about problem, I read the suggested link, but it didn't help me.
My problem is when I try to instance a class.
The error is:
Notice: Undefined variable: userCore in
/Applications/MAMP/htdocs/proyecto_cice/app/web/controller/controllerFormUser.php
on line 74
I know the meaning of this notice, so I use the function class_exists() and I give me true. I used this function, because my first idea was I make a mistake in the class, but it isn't the problem.
I declare this object in load.php file, because I need it in others files too.
I understand the error, but I don't find it. If you can help, I'll be grateful.
The code in the main file where I try instance the class:
<?php
require '../load.php';
function signup($form){
if( $form['pass']== $form['repass'] ){
$exists = $userCore->find_mail( filter_project_form() );
if($exists==''){
$isCorrect = ($userCore->insert_user( filter_project_form() ));
if($isCorrect){echo 'correct';}
}
else{
echo "The user exists now";
}
}
else{
echo 'The passwords must be identical';
}
}
?>
And the file 'load.php' contains:
<?php
//CONFIG
require 'config.php';
require 'constants.php';
//CORE
require 'core/ddbb.php';
require 'core/user.php';
</code>
//CLASS MODEL
require 'model/class_user.php';
//CONTROLLER
require 'controller/controllerUser.php';
//INSTANCIA
$userCore = new User_core();
And the file core/user.php is:
<?php
class User_core extends DDBB_core{
function find_mail($form){
$sql = "SELECT email FROM user WHERE email='".$form['mail']."'";
return $this->executeSelectQuery($sql);
}
}
Thanks
The variable $userCore is not available in your function, as it is defined in the outer scope. You need to make it available:
[...]
function signup($form){
global $userCore;
[...]
By the way, doing things like this is considered bad practice and it goes against the OOP principles. It would be better if you made siginup a method of the UserCore class, or used some kind of rendering utility class for this, where you instead pass the instance of UserCore as one of the arguments to the function instead.

PHP priority functions declarations

I have a question on the way that functions are declared in PHP.
First test :
File "functions.php" => functions toto(){ return "1"; }
Main File
include("functions.php")
functions toto(){ return "main"; }
echo toto();
Second test
File "functions.php" => functions toto(){ return "1"; }
File "functions2.php" => functions toto(){ return "2"; }
Main File
include("functions.php")
include("functions2.php")
echo toto();
Results
The first test work and echo "main"
The second test doesn't work => fatal error "function toto already define"
I make complementary tests :
in first test : put the functions toto() before include doesn't change the result.
Create twice functions toto() in the main file create Fatal Error
Someone can explain me how exactly this work ?
Thanks for reading
The PHP statements from the include family do not copy-paste the content of the included file in the context of the includer. The inclusion happens at runtime.
In your first example, the function toto() defined in the main file is created during the compilation. Then, on the execution, the functions.php file is read and parsed. It generates an error because it attempts to define the function toto() that is already defined.
The same happens in the second example during the inclusion of functions.php. Also, you get the same error if you declare the function toto() two times in the main script.
Either way, the PHP functions and constants cannot be re-declared.
A quick quote from the documentation:
PHP does not support function overloading, nor is it possible to undefine or redefine previously-declared functions.
You can check if a function is already defined (to avoid defining it again) by using the function_exists() PHP function:
function toto() { return 1; }
if (! function_exists('toto')) {
function toto() { return 2; }
}
Points to the topic
You can only name one function toto() else you get Fatal error: Cannot redeclare You can use if(!function_exists('toto')){ /*declaration*/ } to prevent that.
php complies a file complete before including next files, means all functions in a php will be declared, then includes are made. So if the first line includes a file that declares toto(), but the next line declares also toto(). The declaration in the include throw the Fatal error.
The only way to prevent this is for example wrap in the first file if(1){ } around the declaration, so know the Fatal Error comes not from the included file.
Test Case:
//file1.php
<?php
function toto(){ echo __FILE__; }
//file2.php
<?php
include 'file1.php';
function toto(){ echo __FILE__; }
toto();
Call:
php file2.php
Result:
Fatal error: Cannot redeclare toto() (previously declared in file2.php)
//file1.php
<?php
function toto(){ echo __FILE__; }
//file2.php
<?php
include 'file1.php';
if(1){
function toto(){ echo __FILE__; }
}
toto();
Call:
php file2.php
Result:
Fatal error: Cannot redeclare toto() (previously declared in file1.php)

Function and include

I have one file called paths.php that has the following code :
<?php
$path_1="db";
$path_2="files";
?>
This file is included in other files, for example file index.php and the following include : include("paths.php");
In index.php, where I got this include, I also have the following function :
<?php
function explode($value,$separator)
{
/// Into I need take value $path_1 ///
$exp=explode("$separator","$value");
for ($i=0;$i<count($exp);$i++)
{
print "".$exp[$i]."";
}
}
?>
The problem is that I need to the read the value ($value) from the include inside the function scope. I have problems with the function, the include has to be in the function to work.
Is it possible that the function take these values and do not need the include to be inside the function, because if I don't put the include inside it doesn't take correct values?
I'm having a hard time understanding what you mean. But I noticed some problem in your code:
function explode($value,$separator)
{
explode() is a built-in PHP function. You cannot redeclare it. You need to use a different function name for your function.
If you wish to access $path_1 and $path_2 from inside a function you created, you need to use global. For example:
function custom_explode($value,$separator) {
global $path_1, $path_2;
// your other codes
echo 'I can now access $path_1: '.$path_1.' and $path_2: '.$path_2.'!';
}

Unable to access global variable in included file

I am having an unexpected issue with scope. The include documentation (also applies to require_once) says the required file should have access to all variable at the line it was required.
For some reason I am not able to access a class instantiated with global scope inside a function that was required in.
Would anyone know why? I am obviously missing something.
I got it working through a reference to $GLOBALS[], but I still want to know why it is not working.
UPDATE:
The error I am getting is:
Fatal error: Call to a member function isAdmin() on a non-object in <path>.php on <line>
Code:
$newClass = new myClass();
require_once("path to my file");
----- inside required file -----
function someFunction() {
$newClass->someMethod(); // gives fatal error. (see above).
}
Functions define a new scope, so inside a function you cannot access variables in the global scope.
Variable Scope
within user-defined functions a local
function scope is introduced. Any
variable used inside a function is by
default limited to the local function
scope
About included files, the manual states:
When a file is included, the code it
contains inherits the variable scope
of the line on which the include
occurs.
So if you include something in a function, the included file's scope will be that of the function's.
UPDATE: Looking at your code example edited into the question, global $newClass; as the first line of the function should make it working.
$newClass = new myClass();
require_once("path to my file");
----- inside required file -----
function someFunction() {
global $newClass;
$newClass->someMethod();
}
Be aware though that using global can quickly make your code more difficult to maintain. Don't rely on the global scope, you can pass the object to the function as a parameter, or use a Singleton/Registry class (some tend to argue against the latter, but depending on the case it can be a cleaner solution).
The included code doesn't have a scope different than the code surrounding it. For example:
function a() {
echo $b;
}
This will fail even if echo $b is in an included file. If you replace the above with:
function a() {
include 'file.php';
}
... and file.php contains:
echo $b;
... then it's the same thing as if you wrote:
function a() {
echo $b;
}
Think of it this way: whenever you use include / require, the contents of the included file is going to replace the include / require statement, just as if you removed the statement and pasted the contents of the file in its place.
It doesn't do anything else as far as scope is concerned.

"Fatal error: Cannot redeclare <function>"

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

Categories