Retrieving variables from included files - php

I have a php file that includes another one using include()
I defined a variable $something in the included file and that will change depending on a function that runs in the included file.
Now, I want to print that variable in the original file, when I use echo $something it is printing absolutely nothing, help?

Let's just leave aside that this is a poor design choice for a moment :)
You're probably running into a issue where you haven't declared the variable as global inside the function which modifies it.
function foo()
{
global $something;
$something='bar';
}
You will find the PHP manual page on variable scope most educational in this regard!
So why is this a poor design choice? First of all, check out "Are global variables bad?" which answers the question for C++. The answer is really no different for PHP - it can lead to unmaintainable and unreadable code.
There's another (increasingly historical) wrinkle with PHP though - if the 'register_globals' setting is on, a user can set global variables via the URL query string. This can lead to all manner of security problems, which is why this is now turned off by default (never write new code which requires it to be on).
As a wise man once said, "globals are the path to the dark side. globals lead to anger. anger leads to hate. hate leads to suffering" :)

It is possible you have declared your variable in global scope and are trying to use it in functional scope. To get around this use the global command.
$myglobal = 3;
function printMyGlobal() {
global $myglobal; // will not work without this line
echo $myglobal;
}

Use get_defined_vars to debug defined variables

Related

Custom variable which can be used on each page like super globals?

I want a variable to be superglobal, but as am using procedural style I don't think I can make one of my own, so basically the question is that am using a query to retrieve all security control of my website from security table, am checking whether maintenance mode is on/off, if it's on am redirecting it to website under maintenance page, so on each page I need to check the status of variable $maintenance_status, for doing this, i need to call that query on each page, or else am getting an error that undefined variable, moreover if am making a function and including that function file in other pages, it is showing me that $db_connect(which is my db connection variable) is undefined, am including my pages in this sequence
include_once('connection.php');
include_once('functions.php');
/*other scripts goes here*/
Any idea how to pull this status on each page? I thought to make a new file for common queries but is ait a clean solution? moreover I guess am not understanding includes, if I included connection.php before functions.php than why my functions.php is showing undefined variable $db_connect?
You can use a constant for that by using define(). Defines can be set once per script execution and can not be changed during one script execution. They are superglobal - also across files which are being included.
See http://php.net/define or just
define('MY_CONSTANT', 'whatever');
define('MY_OTHER_CONSTANT', false);
function foo() {
if (MY_OTHER_CONSTANT !== true) {
echo MY_CONSTANT;
}
}
foo();
Without more code context on where within your files you are getting the errors, it will be hard to provide any advice. For example, is your reference to $db_connect done from inside a function? If it is, than it will not work unless you have a global $db_connect declaration within that function (to use the $db_connect in the global scope rather than the undefined $db_connect in the function's scope).
While I don't prefer using such global declarations within functions for a number of reasons (I would rather use dependency injection, or get the DB connection via a static singleton function call), that is probably a lesson for another time.
You might be best served anyway to make your query in some sort of init script (like after your connection.php inlcude) and define a constant regarding whether maintenance mode if on or off. Something like this
// assuming you have already made DB query and have a value of true/false on a variable called $is_maint_mode
define('MAINT_MODE', $is_maint_mode);
This would give you a constant MAINT_MODE that is globally available to your code.

PHP Global Variables Issue

I've got a scope problem here. and no idea why its not working, ive got a setup as follows:
functions.php
global $id;
$id = $_GET['id'];
index.php
require_once('functions.php');
echo $id;
now inside functions.php i can echo out $id. however my echo $id; inside index.php is bringing up blank. absolutely nothing.
what am i doing wrong?
In PHP, the global keyword allows you to reference variables in the global scope from inside a local scope - eg to access a global variable inside a function. You don't need global in your example, because you are in the global scope anyway.
I suspect you are showing us a simplified version of what you have, where the issue is in code you haven't shown us.
Why you shouldn't use globals
Confusion like this is part of why using globals is a bad idea and should be avoided.
The alternative is to pass variables around explicitly, so for example if you call a function or instantiate a class from another file, you pass the variable in as a parameter to that function or constructor. Doing this, instead of using global variables, makes it easier to follow what function is accessing what variable because you can follow the trail easier.
You don't need globals between files, only for functions.
Functions.php
<?php
$foobar = "Hello";
?>
Index.php
<?php
include('Functions.php');
echo $foobar;
?>
You shouldn't use globals, but you have it backwards. You declare the variable global after you include its definition:
file1.php:
$name = 'Josh';
file2.php:
require_once('file1.php');
global $name;
echo $name;
#thomasrutter is correct (+1) Global variables areA Bad Thing. Always seek alternatives.
Perhaps you can use $_SESSION (which sort of amounts to the same thing, I know), or declare a class which has a static variable and use a getter() and setter() ? (the latter uis definitely cleaner, but $_SESSION might tie in better with your design, I can't say)
Btw, I hope that functions.php was just an example name, or that you have an extermely simple project.
Otherwise fucntions.php is going to get extermaly large and hard to oversee. If you are going OO then user one file per class, otherwse try to group your functions into separate files (file_management.php, databse.php, forms.php and the like).
If you are just starting out, I would advise you to use Netbeans and document your code with PhpDoc comments which will allow you to generate good documentation which you can view in your browser (including the structure of your coed, what gets declared where, used where, descruptions of function parameters and return values, etc)
Btw, I notice that you use include() I prefer require_once. The _once helps spee dperformnce a little and hte require makes sure that you are aware of missing files more quickly.
Oh, and learn to use Xdebug, which plays well with NetBeans.

PHP variable from other file comes back as NULL

In one PHP file, I have this code:
require_once $_SERVER['DOCUMENT_ROOT'] . '/custom/functions.php';
global $testVar;
var_dump($testVar);
In the functions.php file, I have this at the beginning, followed by a few other functions:
function pr($s) {
echo '<pre>', htmlspecialchars(print_r($s,true)), '</pre>';
}
$testVar = 'hello world';
When running the first file, the variable comes back as NULL. I added the global bit but it shouldn't be necessary. This is part of a Joomla module but I've never had problems including files before, it should just work like regular PHP. Why might this be happening?
First, try to use Joomla's path constants such as JPATH_BASE instead of $_SERVER['DOCUMENT_ROOT']. Joomla has a lot of useful constants, check it's documentation.
I've read your answer, and reading php documentation I tried to find a reason to why you need to use global keyword twice.
First, Variable scope.
The scope of a variable is the context within which it is defined. For the most
part all PHP variables only have a single scope.
(...)
However, 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.
The variable isn't in a function scope, so that's why we thought the NULL was a strange behavior.
But then I read include and found something interesting:
(...)
Any variables available at that line in the calling file will be available
within the called file, from that point forward. However, all **functions**
and **classes** defined in the included file have the global scope.
I can't see any mention about the variables being global in this paragraph. So,it seens that, being cumbersome or not, your solution is the right thing to do when you want to use global variables like that.
In your situation, if doing this is cumbersome, I would create a simple class. If you have just helper functions in your file, create a class Util{} with a lot of methods and $testVar as an attribute.
I have found a solution that seems to work: using the global keyword both when setting the variable initially, and just before I need to use it.
(However this is quite cumbersome, and I'm still not sure why it happens, so if anyone has a better solution, feel free to post.)

PHP best practices: repass variables from config file when calling functions or use global?

I have a program that I use on several sites. It uses require('config.php'); to set any site dependant variables like mysql connect info, paths, etc.
Let's say that I use one of these site-dependant variables in a function, like $backup_path.
This variable was initially declared in config.php, and does not appear in the main program file.
I need to access this variable in function makebackup($table_name); (also in a separate functions.php file).
Is it better to say
makebackup('my_table');
and then use "global $backup_path" inside the function, or is it better to call the function using
makebackup('my_table',$backup_path);
The argument for the first is that it keeps the main program flow simple and easy to understand, without clutter.
The argument for the second is that it might not be obvious that the variable $backup_path exists after some time has passed, and debugging or reworking could be difficult.
Is one or the other of these techniques "standard" among professional programmers? Or should I be using $_SESSION to declare these global variables?
The second alternative,
makebackup('my_table', $backup_path);
is a reusable function and therefore generally preferable. The extra argument is not a big price for reusability.
If you are entirely sure that you'll ever use that function in that particular application only, and for $backup_path only, then maybe consider the global alternative. Even then it's good to check that the global variable actually exists. And be aware that it's extremely difficult to get rid of globals once you start using them.
Remember that you can set a default value for your function:
function makebackup($table, $dir = CONFIG_BACKUP_PATH)
That way you won't have to supply the variable in the default case, you can simply assume that the configured backup path is the default.
This assumes that you are using constants, not global variables.
I'm think you must use Singleton of Factory class config for this purposes.
function makebackup($table)
{
$backup_path = ConfigFactory().getConfig($some_site_specific_data).getBackupPath()
mysqldump($table, $backup_path)
}
Passing references around is far easier to test (you can give mock configuration objects). Globals less so. You can assert that the reference is not null on the method. I would call testability best practice.
Label that global variable
Personally, I have also taken to marking global variables very clearly. If I must use them, I want to be clear about them.
So here, I'd rename $backup_path to $GLOBAL_backup_path. Every time I saw it, I'd know to be careful with it.
An alternative option is using php constants with define().
Your config.php will set constants for every parameter (mysql connection, css style, wathever). Then you will not need to pass variables to functions nor using global.
One downside is that you can define only booleans, floats, strings or integers, no complex data structures.
Not sure there's really a 'right' way to do it, but another option would be something like this:
function makebackup($table, $backup_path = '') {
if ( $backup_path == '' ) {
if ( isset($GLOBALS['backup_path']) ) {
$backup_path = $GLOBALS['backup_path'];
}
else {
die('No backup path provided');
}
}
}
That way you can either pass in the value (for testing and future use) or if you don't pass it in, then the function will look for a possible global variable.

DEFINE vs Variable in PHP

Can someone explain the difference between using
define('SOMETHING', true);
and
$SOMETHING = true;
And maybe the benefits between one or the other?
I use variables everywhere and even in a config type file that is included to everypage I still use variables as I don't see why to use the define method.
DEFINE makes a constant, and constants are global and can be used anywhere. They also cannot be redefined, which variables can be.
I normally use DEFINE for Configs because no one can mess with it after the fact, and I can check it anywhere without global-ling, making for easier checks.
Once defined, a 'constant' cannot be changed at runtime, whereas an ordinary variable assignment can.
Constants are better for things like configuration directives which should not be changed during execution. Furthermore, code is easier to read (and maintain & handover) if values which are meant to be constant are explicitly made so.
There is also a difference in scope.
In the example given by the orignal poster, $SOMETHING will not be accessible within a function whereas define('SOMETHING', true) will be.
define() makes a read-only variable, compared to a standard variable that supports read and write operations.
A constant is very useful when you want access data from inside a function, check this
<?php
function data(){
define("app","hey you can see me from outside the function",false);
$tech = "xampp";
}
data();
echo $tech;
echo app;
?>
If you use a variable you are never going to get the inside value here is what i get
Notice: Undefined variable: tech in D:\xampp\htdocs\data\index.php on line 8
hey you can see me from outside the function

Categories