DEFINE vs Variable in PHP - 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

Related

Do globals interfere with required files in PHP?

I need to edit a variable (array) that is defined outside of the function, so I can use it in another function further in. The easiest way I can think of is to define it as global inside the function, but I have many required files involved as well.
The documentation of global variables says that it can be used "anywhere in the program." Does that imply throughout all files (is it global in a sense of across all files) or is it just the file it's in (locally global, if that makes sense).
I did find a question about globals on this site that suggests passing it by reference, but I have this function implemented extensively in other files and requiring them to have an additional variable in their calls would be obnoxious to say the least.
If you define your variable global within the function, you will be referring to the globally scoped variable, and changes to that variable made within your function will be visible to other functions that use that global variable, whatever files they're in, so long as the inclusion / execution order is correct.
If the file you declare the global in is in memory, then that variable is available for you to use. But, if you don't include or require the file the global is declared in on a certain page, it will not be available to you.
Order is also important. If you try to call the global variable before the include or require of the file you set it in, it will be unavailable.
Globals are shared among all files. By the way, instead of declaring them with global $variable;, you should use $GLOBALS['variable'] to make explicit that you're accessing a global variable.
If a lot of functions grouped in a file require access to some common state, chances are you need to turn them into a class. That's pretty much the definition of a class.
Or you could turn the array into a class and have functions call methods on it.
Perhaps a singleton or a registry (2) could help.
Note that most OOP implementations pass a reference to the object as a method's first parameter, hidden (C++, PHP) or not (C, Python).

PHP basic (noobish) concept question: Constant vs. Function

I have a global "functions.php" file containing functions used throughout my site.
In terms of performance, efficiency, etc – is it better to call one of these functions directly or to define them as constants and call the constant instead? (Or does it matter at all?)
ie
<?php echo site_root(); ?>
vs.
<?php echo SITEROOT; ?>
Thanks
It depends on what site_root() does exactly.
If all it does is something very simple like read from an array and return a string, it doesn't matter whether you use the function, or a constant. Use whatever works best for you.
If the function does something expensive like a database lookup, it is indeed wise to do the call only once, store the result in a constant, and use that in the code.
Adam, another option is to use static vars as a cache inside a function:
function site_root() {
static $result = null;
if (!is_null($result)) {
return $result;
}
// code for defining and returning result only once
}
You can use constants only when your code always require them. And if your code use it only here or there, then don`t use them, as code, that will define them will slow down your main code.

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