DEFINE vs Variable in PHP
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.
Difference between define and simple variable in PHP
Define defines a value, a constant which you can not change while variable means it's value may or will vary.
EDIT:
Both have practical usage. There are sometimes data which should not be changed or it is always the same. For example a hex code of color blue will always be 0000FF
or a database password may never be changed while the session is running.
It's more of a security tool than a performance or readability concern. Once you DEFINE
, there's no way back, but you're sure your data is the same across the whole instance.
PHP | define() vs. const
As of PHP 5.3 there are two ways to define constants: Either using the const
keyword or using the define()
function:
const FOO = 'BAR';
define('FOO', 'BAR');
The fundamental difference between those two ways is that const
defines constants at compile time, whereas define
defines them at run time. This causes most of const
's disadvantages. Some disadvantages of const
are:
const
cannot be used to conditionally define constants. To define a global constant, it has to be used in the outermost scope:if (...) {
const FOO = 'BAR'; // Invalid
}
// but
if (...) {
define('FOO', 'BAR'); // Valid
}Why would you want to do that anyway? One common application is to check whether the constant is already defined:
if (!defined('FOO')) {
define('FOO', 'BAR');
}const
accepts a static scalar (number, string or other constant liketrue
,false
,null
,__FILE__
), whereasdefine()
takes any expression. Since PHP 5.6 constant expressions are allowed inconst
as well:const BIT_5 = 1 << 5; // Valid since PHP 5.6 and invalid previously
define('BIT_5', 1 << 5); // Always validconst
takes a plain constant name, whereasdefine()
accepts any expression as name. This allows to do things like this:for ($i = 0; $i < 32; ++$i) {
define('BIT_' . $i, 1 << $i);
}const
s are always case sensitive, whereasdefine()
allows you to define case insensitive constants by passingtrue
as the third argument (Note: defining case-insensitive constants is deprecated as of PHP 7.3.0 and removed since PHP 8.0.0):define('FOO', 'BAR', true);
echo FOO; // BAR
echo foo; // BAR
So, that was the bad side of things. Now let's look at the reason why I personally always use const
unless one of the above situations occurs:
const
simply reads nicer. It's a language construct instead of a function and also is consistent with how you define constants in classes.const
, being a language construct, can be statically analysed by automated tooling.const
defines a constant in the current namespace, whiledefine()
has to be passed the full namespace name:namespace A\B\C;
// To define the constant A\B\C\FOO:
const FOO = 'BAR';
define('A\B\C\FOO', 'BAR');Since PHP 5.6
const
constants can also be arrays, whiledefine()
does not support arrays yet. However, arrays will be supported for both cases in PHP 7.const FOO = [1, 2, 3]; // Valid in PHP 5.6
define('FOO', [1, 2, 3]); // Invalid in PHP 5.6 and valid in PHP 7.0
Finally, note that const
can also be used within a class or interface to define a class constant or interface constant. define
cannot be used for this purpose:
class Foo {
const BAR = 2; // Valid
}
// But
class Baz {
define('QUX', 2); // Invalid
}
Summary
Unless you need any type of conditional or expressional definition, use const
s instead of define()
s - simply for the sake of readability!
PHP Should I use CONSTANTS or VARIABLES
First I'd like to propose not to follow those advices using constants for configuration. This will make your code hard to test (against a test environment) plus it's very unconventional to deploy code where you have to edit code for application configuration.
You will most of the time use variables. This brings the question to when should you use constants. Those points come to my mind:
- Use constants for Magic numbers.
- Use constants to express semantic for a defined set of distinct values where the value itself doesn't matter. E.g. it doesn't really matter what values these constants will have:
STATE_NEW
,STATE_OLD
,STATE_DELETED
#Define VS Variable
Well, there is a great difference. You can change the value of width
, you can take its address, you can ask for its size and so on. With WIDTH
, it will be just replaced with a constant 10
everywhere, so the expression ++WIDTH
doesn't make any sense. Ono the other side, you can declare an array with WIDTH
items, whereas you cannot declare an array with width
items.
Summing it up: the value of WIDTH
is known at compile time and cannot be changed. The compiler doesn't allocate memory for WIDTH
. On the contrary, width
is a variable with initial value 10, its further values are not known at compile time; the variable gets its memory from the compiler.
Global vs. Define
define
. You can't change its value later, and its value is always available in all scopes, tersely.
How efficient is define in PHP?
'define' operation itself is rather slow - confirmed by xdebug profiler.
Here is benchmarks from http://t3.dotgnu.info/blog/php/my-first-php-extension.html:
pure 'define'
380.785 fetches/sec
14.2647 mean msecs/first-responseconstants defined with 'hidef' extension
930.783 fetches/sec
6.30279 mean msecs/first-response
broken link update
The blog post referenced above has left the internet. It can still be viewed here via Wayback Machine. Here is another similar article.
The libraries the author references can be found here (apc_define_constants) and here (hidef extension).
PHP Define var = one or other (aka: $var=($a||$b);)
Update
I've managed to create a function for you that achieves exactly what you desire, allowing infinite arguements being supplied and fetching as you desire:
function _vars() {
$args = func_get_args();
// loop through until we find one that isn't empty
foreach($args as &$item) {
// if empty
if(empty($item)) {
// remove the item from the array
unset($item);
} else {
// return the first found item that exists
return $item;
}
}
// return false if nothing found
return false;
}
To understand the function above, simply read the comments above.
Usage:
$a = _vars($_POST['x'], $_SESSION['x']);
And here is your:
Example
It is a very simply ternary operation. You simply need to check the post first and then check the session after:
$a = (isset($_POST['x']) && !empty($_POST['x']) ?
$_POST['x']
:
(isset($_SESSION['x']) && !empty($_SESSION['x']) ? $_SESSION['x'] : null)
);
Related Topics
What Ocr Options Exist Beyond Tesseract
How to Install Pdo_Sqlsrv on My Windows 2008 Server 2008 R2
Fatal Error: Call to Undefined Method MySQLi_Result::Fetch_All()
Round to Max Thousand, Hundred etc in PHP
How to Add Dynamic Dropdown List Column on Laravel 5.3 Registration
Whats the Easiest Way to Determine If a User Is Online? (Php/Mysql)
Pull All Images from a Specified Directory and Then Display Them
Mysqli_Real_Connect(): (Hy000/2002): No Such File or Directory
Adding Three Months to a Date in PHP
Replace the Variable Price Range by the Chosen Variation Price in Woocommerce 4+
Php: Setting a Timezone by Utc Offset
Laravel 4 Removing Public from Url
Get Variable from PHP File Using Jquery/Ajax
PHP Exec - Check If Enabled or Disabled
Twig Iterate Over Object Properties
Looping Through Query Results Multiple Times with MySQLi_Fetch_Array