require_once the same file multiple time? - php

I have a config file that contain credential information to connect to an API
I include my config file in 2 functions in 2 different file
In the first called function, I have my credential variables but when I call my second function, my credential variables are empty.
index.php
<?php
require_once("./connector/hot/hotelbeds/book.php");
if($_REQUEST['connector'] == 'hotelbeds')
{
require_once("connector/hot/hotelbeds/validate.php");
validate_hotelbeds($_REQUEST);
}
$booking_output = book_hotelbeds($_REQUEST);
?>
validate.php
<?php
function validate_hotelbeds($results)
{
$account = $results['header']['account'];
include_once("./connector/hot/hotelbeds/account_config/$account/config.php");
// $url contain my url
$validate = curl_get($url , $results);
}
?>
book.php
<?php
function book_hotelbeds($results)
{
$account = $results['header']['account'];
include_once("./connector/hot/hotelbeds/account_config/$account/config.php");
// $url is empty
$book = curl_get($url , $results);
}
?>
config.php
<?php
$url = "http://www.websitelink.com";
?>

The first time you require it, the variables will be introduced.
When you require it again from inside a function, the file has already been required so it is ignored.
The variables are outside the scope of the function at this point, so if you have to you would need to access them by declaring them as global.
Perhaps a better idea would be do declare those variables as constants instead, which means they will be available within the function scopes:
$myVariable = 'hello';
define('MY_CONSTANT', 'world');
echo 'Global scope: ', $myVariable, MY_CONSTANT, PHP_EOL; // helloworld
function myFunction()
{
echo 'Function scope: ', $myVariable, MY_CONSTANT, PHP_EOL; // world
}
function myGlobalFunction()
{
global $myVariable;
echo 'Function scope using global: ', $myVariable, MY_CONSTANT, PHP_EOL; // helloworld
}
Example.

Put your include_once("./connector/hot/hotelbeds/account_config/$account/config.php"); into index instead. Then if you wanted to use the var $url you would need a line above stating that you want that global var: global $url;.
Also I suggest changing $url name and change it to constant like: const API_URL = 'website_url'

Functions require_once and include_once include file only on time for one call of script. Because you include files book.php and validate.php in index.php then PHP include config.php only one time.
You can include config.php in index.php and use global directive inside your function.
Or you can just use functions include and require. These functions include one file to script many times - on each call.

Related

php how to access language variable inside a function when the language page has already been included?

My php script includes another en.php file which contains the required english strings. This same page also calls a html page which uses the file and formats it using the contents of the en.php file.
I have a function in this script which references variables defined in the included script but I am getting error messages of the variable not being found. If I reference the variable outside the function, the variable is accessed correctly. Why can I not access these variables inside the function?
en.php
<?php
$lang_yes = 'Yes';
$lang_no = 'No';
?>
example.php
<?php
include_once('addons/assq/lang/en.php');
echo $lang_yes;
$q1 = convertToYesOrNoString(0);
echo $q1;
function convertToYesOrNoString($value){
//include_once('addons/assq/lang/en.php');
if ($value == 0){
return $lang_no;
}else if ($value == 1){
return $lang_yes;
}else{
return "---";
}
}
?>
My output is as follows:
Yes
Undefined variable: lang_no in example.php on the line in the function
I tried including the en.php directly into the function but that did not work either. How can I access these variables inside my function while including the file as implemented above?
You can either define it as a constant, pass it as an argument or declare it as a global within the function:
function convertToYesOrNoString($value){
global $lang_no, $lang_yes;
//...
}
That's a scope issue. That variable $lang_no will not be accessed under that function , you need to pass that as a parameter instead to the function definition.
function convertToYesOrNoString($value,$lang_no){ //<--- Like this.
Since you have mentioned that you have a lot of parameters .. you can write a turnaround like this...
Your en.php
<?php
//Map all those variables inside an array as key-value pair. as shown
$varArray=array('lang_yes'=>'Yes','lang_no'=>'No');
Some test.php
<?php
include('en.php');
function convertToYesOrNoString($varArray)
{
extract($varArray);
echo $lang_yes; // "prints" Yes
echo $lang_no; // "prints" No
}
convertToYesOrNoString($varArray);

how to access a php variable inside a function from an included file

I have a file called test1.php with lots of variable and some function definitions. I am trying to include this file to one another file called test2.php and use the variables and the functions.
test1.php
$i = "a";
$ii = "b";
$iii = "c";
function test1a(){ return "lol"; }
test2.php
function test2a(){ include 'test1.php'; return $i; }
function test2b() { include 'test1.php'; return test2c(); }
function test2c(){ include 'test1.php'; return $iii; }
function test2d() { include 'test1.php'; return test1a(); }
index.php
include 'test2.php'
echo test2a();
echo test2b();
echo test2c();
echo test2d();
Reason:
I have the same code base in two different servers. Only the test2.php file will be different.Each server will have different values inside the test2.php but with same variable name. test2.php will act somewhat like a localization file.
My problem is some of the variables or not showing up. Is there a better way to do this. I don't want to include the file in every function.
Thanks.
Just do it the other way round:
put all the different variables into one file in to an array, without any functions:
//config.php
$config['setting1'] = "val1";
$config['setting2'] = "val2";
$config['setting3'] = 42;
...
and further:
//index.php
include_once("config.php");
echo $config['setting1'];
....
now you may have different configs on different servers w/o need to change any functions.
You are trying to include file with one function several times. Functions are always global. So second include gives you an fatal error Fatal error: Cannot redeclare test1a() (previously declared in [..]).
You should put this function to separate file and use include_once.

How aright use globals elements

Good day.
I have problems when i use globals element in some files which include in one file.
Structure my files you can see down:
Files:
-index.php
--function.php
--globals.php
--lang.php
--allfunction.php
Code all pages you can see down:
Code index.php:
<?
session_start();
require_once("./function.php");
select();
?>
Code function.php:
<?php
require_once("./globals.php");
require_once(dirname(__FILE__)."/lang.php");
include_once Language(3);
require_once(dirname(__FILE__)."/allfunction.php");
?>
Code globals.php:
<?
$dirang = './';
$langfile = 'lang.php';
$test = 'hello';
}
?>
Code lang.php:
<?
Language($rem){
return $GLOBALS["langfile"]; //ex.
}
?>
Code allfunction.php:
<?
echo $GLOBALS["test"]; //ex.
}
?>
I get problrem when i use $GLOBALS["test"] in allfunction.php.
I get error Undefened index test in allfunction.php on line ....
Tell me please why i get it error and how aright use global element in allfunction.php ?
you should write globals inside file where you use theys, for ex. if globals you use in allfunction.php you must write global variables in this file(in which you use them)
Not use a separate file with global variables.
Don't use globals. Store your variables in static Config or Registry class instead. Also have a read about singleton design pattern.
Example:
config.php
<?php
class Config
{
static $var1 = '...';
static $var2 = '...';
public static function init()
{
self::$var2 = 1+1; //expressions go here
}
}
Config::init();
usage.php
<?php
require_once 'config.php';
function x()
{
$someKindOfSetting = Config::$var1;
}

PHP including files inside classes

Just a quick question, but I've been working on a small MVC framework and noticed something.
For example:
--PHP file--
class loadFiles{
function __construct($file = NULL){
include $file . '.php';
}
}
$loadfiles = new $loadFiles('crucialsettings');
echo $randomstring; //Throws an error
--crucialsettings.php--
<?php
$randomstring = 'hello';
?>
I only just realised that files included inside an objects scope are inaccessable from the global scope. What is the best way to include a file inside an object so it can be accessed globally?
I would like to be able to:
$loadfiles->settings();
$loadfiles->classes();
$loadfiles->passwords();
I want to build a class that handles global file includes.
It doesn't matter where you include or require code from in PHP. The interpreter is pretty linear in it's first definition pass, that is to say that it will basically compress all of the included / required files into one large file in the exact order in how it was read.
One thing to note about this is that scope does change. but everything is applied to the "global" scope. You can always import something from the global scope into your current scope using the "global" keyword to declare a variable prior to using it. So when you want to use a "global" variable from another script just ask for it.
A little example...
a.php
include('b.php');
global $myVar;
echo $myVar;
b.php
include('c.php');
c.php
$myVar = 'Hello World';
What the interpreter see's this code as after it's first pass
// In global scope
$myVar = 'Hello World'
// In a.php scope
global $myVar;
echo $myVar;
In short from your php file simply add the line
global $randomstring;
After you include the crucialsettings.php file and your echo will work.
Appears that your framework here is too reliant on non-OOP for its innards. Not a preferable way to build up, but you can do what you want by cycling through list of variables and making them part of your class/instance scope. A rather helpful function here is get_defined_vars();
Lets say you have files a.php, b.php and c.php. Each looks like this:
a.php: <?php $a = "AAAAAA";
b.php: <?php $b = "BBBBBBBBBB";
c.php: <?php $c = "CCCCCCCCCCCCCCCCCCCCCCCCCCC";
class mystuff {
function include_with_vars( $____file ) {
// grab snapshot of variables, exclude knowns
$____before = get_defined_vars();
unset( $____before['____file'] );
// include file which presumably will add vars
include( $____file );
// grab snapshot of variables, exclude knowns again
$____after = get_defined_vars();
unset( $____after['____file'] );
unset( $____after['____before'] );
// generate a list of variables that appear to be new
$____diff = array_diff( $____after, $____before );
// put all local vars in instance scope
foreach( $____diff as $variable_name => $variable_value ) {
$this->$variable_name = $variable_value;
}
}
function __construct($file = NULL){
$this->include_with_vars( "a.php" );
$this->include_with_vars( "b.php" );
$this->include_with_vars( "c.php" );
}
}
$t = new mystuff();
echo "<PRE>";
print_r( $t );
This program will now take local variables from your include() directives and put them in the class scope:
mystuff Object
(
[a] => AAAAAA
[b] => BBBBBBBBBB
[c] => CCCCCCCCCCCCCCCCCCCCCCCCCCC
)
In other words, your local variables from file a.php ($a) are now $t->a.

Undefined variable error on a variable inside an included file

I'm including this file to collect one of its variables. File path is correct and i don't get file include errors. But when i try to print a variable inside that file it gives undefined variable error. Following is the code.
include_once($path . "folder/file.php");
echo($code);
There is a php class. inside the class there is a login function . Within that function I'm including another file assume it's funtions.php.
functions.php has above code in it.
Inside functions.php file i include this file which contains the variable i'm looking for (assume it's test.php).
test.php looks like this (inside php tags)
$code="something";
$another_variable="something else";
so now like i said before when i include this inside functions.php and print $code it why does it gives an undefined error?
Full code
function log($user, $pass) {
global $config;
$this->get_available_accounts();
if (isset($this->Users_obj[$user])) {
if ($this->Users_obj[$user]->userName == $user && $this->Users_obj[$user]->passWord == $pass) {
delete_cache_full();
$_SESSION['username'] = $user;
$_SESSION['log'] = true;
$_SESSION['usergroup']=$this->Users_obj[$user]->level;
$this->set_permission_session($_SESSION['usergroup']);
include_once $config->path . 'config.php';
$newUpdate2=showUpdates2();
if(!empty($newUpdate2)){
$_SESSION['updateremindlater']=$newUpdate2['date'];
}
//file
include_once $config->path . 'functions.php';
$func = new UserFuncs();
$func->validate();
include_once $config->path . 'view/ViewDashboard.php';
return true;
}
}
thats the function im including this file into. include_once $config->$path . 'functions.php'; includes functions.php file
functions.php looks like this
include_once($path. "folder/config.php");
echo($code);
and config.php looks like
$code = "ERGERW2342HV3453WERWEER";
$host_name = "SERV345WERFDGDDFGDGF";
$return_code = "DFGDFSDGFS";
$vurl = "YUIYUJHGJ";
$next_val ="AWERFDFVDV";
$val_exp = "NMGHJGJGH";
Help much appreciated!
Just guessing that you've included config.php somewhere else before, and that it's not being included again due to include_once. Therefore the variables are not created in the scope you're including it in the second time.
This could be a problem with variable scope, where you are trying t access the variable from somewhere (e.g. a function) where it is not available to that particular object (you did mention that you included the file within a class).
I agree with deceze and hakre, it's very hard to answer this question without seeing your code.

Categories