PHP includes/require in a file and all functions inside it - php

I have a file which I include say:
require_once("../../constructor/database.php");
$stuff_inside_include_file->doThis() ; //ACCESSIBLE
function createUser(){
$stuff_inside_include_file->doThat(); //NOT-ACCESSIBLE (object not found)
}
function deleteUser(){
. ...
If I move the require statement into the scope of the function, then it works. Otherwise, it doesn't. Is there a better solution?
Thank you in advance.

You can try:
function createUser($stuff_inside_include_file){
$stuff_inside_include_file->doThat();
}
it should work, I think.

The best solution would be to not create global variables, but this would also work:
require_once("../../constructor/database.php");
$stuff_inside_include_file->doThis() ; //ACCESSIBLE
function createUser(){
global $stuff_inside_include_file;
$stuff_inside_include_file->doThat(); //ACCESSIBLE
}
function deleteUser(){
. ...
But really.. "Think globally, act in local scope".

I believe this is an issue with the variable not being global.
e.g.
$i = 10;
function pooppoop() {
$i = 11;
#this only sets the local variable i to 11
}
So you will want to put a global $i; at the top of your function. Obviously replace $i with the variable you are having trouble accessing.

I looks like the $stuff_inside_include_file variable is in the global scope, so you should be able to do this:
function createUser(){
global $stuff_inside_include_file;
$stuff_inside_include_file->doThat();
}

Related

Is there a way to set Global Variables to be available by default within PHP functions?

Is there any way to do this / specify this in the php.ini configuration file? It would be really nice, at least for local server purposes, just to write functions without having to write the global keyword every time a global variable is used within the method.
Any way to do this?
EDIT:
What I mean is being to simply write this:
Example file "index.php":
$MY_ARRAY = array();
include("functions.php");
And then in "functions.php":
function addToArray($pMessage) {
$MY_ARRAY[] = "<a href='somelink.php'>$pMessage</a>";
}
Instead of:
And then in "functions.php":
function addToArray($pMessage) {
global $MY_ARRAY;
$MY_ARRAY[] = "<a href='somelink.php'>$pMessage</a>";
}
Yeah! You can setup a prepend file in PHP.
See: http://www.php.net/manual/en/ini.core.php#ini.auto-prepend-file
I still do not understand the purpose. But if I need to just remove the GLOBAL keyword from mentioning everytime, I would prefer to use a class with static array.
Something like this:
<?php
// Config.php
class Config {
public static $MY_ARRAY = array();
}
?>
And then include this file from your loader just call like this:
function addToArray($pMessage) {
Config::$MY_ARRAY[] = "<a href='somelink.php'>$pMessage</a>";
}
That will work.

Unset XML element function not working

This is what I have.
$filename= asql($_GET['filename']);
$fullfile = "xml/".$filename;
function delete_book_id($ids){
$data = simplexml_load_file($fullfile);
$data_count = count($data->item);
for($i = 0; $i < $data_count; $i++)
{
//basically what you want to remove
if(($data->item[$i]->id == $ids))
{
unset($data->item[$i]);
}
}
file_put_contents($fullfile, $data->saveXML());
}
lets say $fullfile is xml/name.xml and the file exists in our folder. Where the variable is called in the function it should work right?
If I replace the variable in the function with xml/name.xml it will work, but using the variable causes the page to break and not reload nor will it remove the line it is supposed to unset. Will the function not accept variables, or am I missing something here?
I have also tried using "xml/".$filename in place of the variable in the function. No luck there either.
$fullfile is defined outside of the function. It's undefined inside of it. Use global $fullfile; within function or define it there.

Joomla module and variables within functions

I have created a module in Joomla and all is working fine, but when I put a function in and try and access a variable it does not work, but if I echo it outside the function it is ok
$item_img = $params->get('item_img','modules/mod_k2_mobile/images/item_icon.gif');
// not working
function GetIMG(){
global $item_img;
echo "item".$item_img;
}
GetIMG();
// working
echo "item".$item_img;
why?
I would advice you not to use any global variables as long as you can avoid it. Can't you change your function declaration to something like "GetIMG( $item_img )"?
If you still want to use a global variable, this should work:
**global $item_img;**
$item_img = $params->get('item_img','modules/mod_k2_mobile/images/item_icon.gif');
// not working
function GetIMG(){
global $item_img;
echo "item".$item_img;
}
GetIMG();
// working
echo "item".$item_img;
I hope it helps!

php newbie question: global variables for web

i'd like to set up some global variables for storing several things.
i've tried it like this:
function init_web()
{
$webname = "myweb";
$web['webname'] = $webname;
$web['server_root'] = $_SERVER['DOCUMENT_ROOT']."/$webname/";
$web['lang']="en";
}
the problem is that i can't access those variables inside of functions ..
i've tried using global $web; but didnt help.
what's the trick to get it global?
thanks
While you'll get the usual "global variables are bad" crying, here's the basics:
$web = array(); // define the var at the "top level" of the code tree, outside any functions/classes.
function init_web() {
global $web; // make it visible in the function
$web['lang'] = 'en'; // make some settings
}
basically, you had it, but hadn't defined the variable outside the function. Just saying 'global' within the function won't magically create one outside the function - it already has to exist before you try to "internalize" it to the function and change/access its contents.
You are on the right track:
$web = array();
function init_web()
{
global $web;
$webname = "myweb";
$web['webname'] = $webname;
$web['server_root'] = $_SERVER['DOCUMENT_ROOT']."/$webname/";
$web['lang']="en";
}
You can define them constant
define('WEBNAME',"myweb");
and can use everywhere in your application because constant are global in nature by default.
and this is the way to store constant as constant as they never changed dynamically until you move to new server or change configuration.
you can use session variables:
session_start(); // at the top of the php page
function init_web()
{
$webname = "myweb";
$_SESSION['webname'] = $webname;
$_SESSION['server_root'] = $_SERVER['DOCUMENT_ROOT']."/$webname/";
$_SESSION['lang']="en";
}
now they can be 'globally' accessable :-)
Declare $web outside the function and reference it inside with the $GLOBALS superglobal:
// Declare in global scope
$web = array();
function init_web()
{
$webname = "myweb";
// Access via superglobal in function scope
$GLOBALS['web']['webname'] = $webname;
$GLOBALS['web']['server_root'] = $_SERVER['DOCUMENT_ROOT']."/$webname/";
$GLOBALS['web']['lang']="en";
}
If you're just storing scalar values (strings, ints, floats - not arrays, objects), you should use define().
This will make your configurations global and constant.
As to answer your question,
First define your variables outside the scope of that function (perhaps in a config file) and then use the global keyword to make it global when you need them.

run function block in context of global namespace in PHP

So the senario is that I want to have a custom function for requiring libraries. Something like:
define('E_ROOT', str_replace('//','/',dirname(__FILE__)));
/* ... */
function e_load($fn, $allowReloading = FALSE) {
$inc = E_ROOT.'/path/here/'.$fn.'.php';
if($allowReloading)
require $inc; // !!!
else
require_once $inc; // !!!
}
The problem being that require and require_once will load the files into the namespace of the function, which doesn't help for libraries of functions, classes, et cetera. So is there a way to do this?
(Something avoiding require and require_once altogether is fine, as long as it doesn't use eval since it's banned on so many hosts.)
Thanks!
Technically include() is meant to act as though you're inserting the text of included script at that point in your PHP. Thus:
includeMe.php:
<?php
$test = "Hello, World!";
?>
includeIt.php:
<?php
include('includeMe.php');
echo $test;
?>
Should be the exact same as:
<?php
/* INSERTED FROM includeMe.php */
$test = "Hello, World!";
/* END INSERTED PORTION */
echo $test;
?>
Realizing this, the idea of making a function for dynamically including files makes about as much sense (and is about as easy to do) as having dynamic code all-together. It's possible, but it will involve a lot of meta-variables.
I'd look into Variable Variables in PHP as well as the get_defined_vars function for bringing variables into the global scope. This could be done with something like:
<?php
define('E_ROOT', str_replace('//','/',dirname(__FILE__)));
/* ... */
function e_load($fn, $allowReloading = FALSE) {
$prev_defined_vars = get_defined_vars();
$inc = E_ROOT.'/path/here/'.$fn.'.php';
if($allowReloading)
require $inc; // !!!
else
require_once $inc; // !!!
$now_defined_vars = get_defined_vars();
$new_vars = array_diff($now_defined_vars, $prev_defined_vars);
for($i = 0; $i < count($new_vars); $i++){
// Pull new variables into the global scope
global $$newvars[$i];
}
}
?>
It may be more convenient to just use require() and require_once() in place of e_load()
Note that functions and constants should always be in the global scope, so no matter where they are defined they should be callable from anywhere in your code.
The one exception to this is functions defined within a class. These are only callable within the namespace of the class.
EDIT:
I just tested this myself. Functions are declared in the global scope. I ran the following code:
<?php
function test(){
function test2(){
echo "Test2 was called!";
}
}
//test2(); <-- failed
test();
test2(); // <-- succeeded this time
?>
So the function was only defined after test() had been run, but the function was then callable from outside of test(). Therefore the only thing you should need to pull into the global scope are your variables, via the script I provided earlier.
require_once E_ROOT.$libName.'.php';
KISS
Instead of doing this...
$test = "Hello, World!";
... you could consider doing this ...
$GLOBALS[ 'test' ] = "Hello, World!";
Which is safe and consistent in both local function context, and global include context. Probably not harmful to visually remind the reader that you are expecting $test to become global. If you have a large number of globals being dragged in by your libraries maybe there's justification for wrapping it in a class (then you have the benefit of spl_autoload_register which kind of does what you are doing anyhow).

Categories