Am I using these global variables correctly? - php

I'm a newbie to php, and I'm in the process of hacking through some moodle code for a prototype.
Anyhows I have some data Id like passed from file1.php to file2.php, for which Im using global variables. The values are intialized in file2 and I need them for use in file1. Here's how I go about it
file1.php
<?php// top of file 1
global $content; // discussion content // line 3
file2.php
global $content;// line 3379
$content=$post->subject;
Back in file1.php
echo 'global scope'.$content; // this is always empty// line 168
Am I missing something here?
Attached files file1.php and file2.php

You use global to get a global variable
//file 1
$a = "im a global variable";
function foo(){
global $a;
echo $a;
}
//file 2
require "file1.php";
function foo2(){
global $a;
echo $a;
}

Just sharing a thought,
suppose in file1, you have $content = "myID";
and in file2, if you include("file1.php"), you can access by doing,
global $content;
var_dump($content) will output string 'myId' (length=4)

Related

PHP templating and variable scope

i am trying to find out a way to pass non global variables to included document.
page1.php
function foo()
{
$tst =1;
include "page2.php";
}
page2.php
echo $tst;
How can i make that variable be visible ? and how would i do this php templating so i can split header body and footer for html pages. like in a wordpress it has custom wp functions but i dont see them declaring external files to use them.
big thanks in advance.
I think you are not exactly understanding what is going on. Page 1 should probably be doing the echoing. So you include page 2 and the foo function is now available. You need to call it so that it actually executes. Use the global keyword to bring a global variable into the function scope. Then you can echo it.
page1:
include "page2.php";
foo();
echo $test;
page 2:
function foo()
{
global $test;
$test =1;
}
Variables in a function are not seen outside of them when they are not global. But an include in a function should be seen inside the second file.
$test="Big thing";
echo "before testFoo=".$test;
// now call the function testFoo();
testFoo();
echo "after testFoo=".$test;
Result : *after testFoo=Big thing*
function testFoo(){
// the varuiable $test is not known in the function as it's not global
echo "in testFoo before modification =".$test;
// Result :*Notice: Undefined variable: test in test.php
// in testFoo before modification =*
// now inside the function define a variable test.
$test="Tooo Big thing";
echo "in testFoo before include =".$test;
// Result :*in testFoo before include =Tooo Big thing*
// now including the file test2.php
include('test2.php');
echo "in testFoo after include =".$test;
// we are still in the function testFoo() so we can see the result of test2.php
// Result :in testFoo after include =small thing
}
in test2.php
echo $test;
/* Result : Tooo Big thing
as we are still in testFoo() we know $test
now modify $test
*/
$test = "small thing";
I hope that made the things more clear.

require_once the same file multiple time?

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.

How to better realise include?

I currently have 3 files, 1 return array, 2 is command file that manipulate all other and 3 is function file,i include array and function file in command file. How to make array visible in function file, should i use second include or there another way?
file 1
return $arr = array(...);
file 2
function FuncName(){ $arr[1] = '1111';}
file 3
include_once 'file 1';
include_once 'file 2';
$arr[2] = '2222'
It's simple. You can use return inside included file.
//main.php
include_once 'functions.php';
$array = include 'array.php';
goGoArray($array);
// functions.php
function goGoArray($array){
var_dump($array);
}
// array.php
return array(1,23,456,7890);
But, if you what global, use global.
//main.php
include_once 'functions.php';
$array = include 'array.php';
goGoArray();
// functions.php
function goGoArray(){
global $array;
var_dump($array);
}
// array.php
return array(1,23,456,7890);
P.S. But globals are very, very bad.

PHP require/include file

I have the following program Structure:
Root directory:-----index.php
|-------TPL directory
|-------------header.php
|-------------index.php
|-------------footer.php
php file loading structure:
Root directory:index.php ----require/include--->tpl:index.php
|----require/include-->header.php
|----require/include-->footer.php
Root index.php :
<?php
function get_header(){
require('./tpl/header.php');
}
function get_footer(){
require('./tpl/footer.php');
}
$a = "I am a variable";
require('./tpl/index.php');
TPL:index.php:
<?php
get_header();//when I change require('./tpl/header.php'); variable $a can work!!
echo '<br />';
echo 'I am tpl index.php';
echo $a;
echo '<br />';
get_footer();//when I change require('./tpl/footer.php'); variable $a can work!!
TPL:header.php:
<?php
echo 'I am header.php';
echo $a;//can not echo $a variable
echo '<br/>';
TPL:footer.php:
<?php
echo '<br />';
echo $a;//can not echo $a variable
echo 'I am footer';
For some reason when I used function to require header.php and footer.php my variable $a doesn't get echoed. It works fine if I use header.php or footer.php on its own. I do not understand what the problem is. What do you think is the issue here?
Your issue is probably just scope of a function does not automatically include global variables. Try setting $a to global like global $a;, example below for your get_header() function:
function get_header(){
global $a; // Sets $a to global scope
require('./tpl/header.php');
}
Using the include inside a function includes the code directly in that function. Therefore the variable is a locally in that function accessable variable - it is not set outside the function.
If you require/include without a function $a becomes a global variable.
make your variable As Global
global $YourVar;

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.

Categories