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

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.

Related

scope of a global variable in drupal module

What is the scope of a 'global' variable inside a module in Drupal? I created a module for a custom block and need to know how long the global stays set for so I know how to use them. Do they stay across the website instance, or only once for the page. For example in the following code drupal_set_message gets called once every time I load a page with the block. Can I be sure the 'global' variable is refreshed each time the block is loaded?
<?php
global $my_array;
function fill_array()
{
global $my_array;
if(!isset($my_array))
{
drupal_set_message("filling the array");
$my_array = array();
// code to fill array up...
}
}
Check out what documentation says:
http://php.net/manual/en/language.variables.scope.php
Global variables are by default available to all global code. But if you want to use them inside you function you have to declare them as global first.
And any kind php variable has lifetime no longer then one "page call". So with your next page call all the values are lost.
If you want to keep some value longer than single execution you must use php sessions or cookie or file or database....to store them there.
I know that this is an old question but scope is more tricky than this.
Drupal executes a block of PHP in a function context using eval() so variables defined at the top level within your PHP code are not in the global context unless they are explicitly set as global.
In other words, your code has three contexts, not the normal two.

Using PHP variable from one include into another

I have 2 includes on a page. Let's say they're the header and footer:
<?php
include('header.php');
include('footer.php');
I need to use a variable from the footer in the header. Is this possible?
Create another include or put the logic for the var into the main Script.
Unless there's a reason you can't, the simple solution is to set the variable used in inc2 in inc1 instead.
When a script is included outside of any function, the script executes in global scope, so anything it sets or defines that is scoped will have global scope. If a script is included within a local scope (such as in a function), the script executes in the same scope, so anything it defines is local. Note the included script can access variables local to a function.
function foo($x) {
$bar = 'bam';
include 'script.php'; # script.php can access $x and $bar
}
However, global variables can be problematic. A better approach is to break down tasks into separate modules. Most modules are library scripts: they only define things (functions, classes) and don't execute anything directly. The entry point (the top level script) doesn't define anything; instead, it serves to connect everything and as a starting-off point for computation. Here's a simple example with a database connection:
<?php
include_once('DB.php');
include_once('header.php');
include_once('footer.php');
$db = DB::connect();
header($db);
footer($db);
While technically $db is a global variable (note that this is merely sample code, rather than production code), it's not to be accessed anywhere outside this script. Instead, it's passed around according to the rules of capabilities (which was designed for security purposes, but the rules are actually just good OOP principles).

Retrieving variables from included files

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

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.

Categories