Is it necessary to Initialize / Declare variable in PHP? - php

Is it necessary to initialize / declare a variable before a loop or a function?
Whether I initialize / declare variable before or not my code still works.
I'm sharing demo code for what I actually mean:
$cars = null;
foreach ($build as $brand) {
$cars .= $brand . ",";
}
echo $cars;
Or
foreach ($build as $brand) {
$cars .= $brand . ",";
}
echo $cars;
Both pieces of code works same for me, so is it necessary to initialize / declare a variable at the beginning?

PHP does not require it, but it is a good practice to always initialize your variables.
If you don't initialize your variables with a default value, the PHP engine will do a type cast depending on how you are using the variable. This sometimes will lead to unexpected behaviour.
So in short, in my opinion, always set a default value for your variables.
P.S.
In your case the value should be set to "" (empty string), instead of null, since you are using it to concatenate other strings.
Edit
As others (#n-dru) have noted, if you don't set a default value a notice will be generated.

You had better assign it an empty string $cars = '';, otherwise (in case you have error reporting on) you should see a notice:
Notice: Undefined variable: cars
PHP will assume it was empty and the resultant string will be the same, but you should prefer not to cause an extra overhead caused by a need of logging that Notice. So performance-wise it is better to assign it empty first.
Besides, using editors like Aptana, etc, you may wish to press F3 to see where given variable originated from. And it is so comfortable to have it initialized somewhere. So debugging-wise it is also better to have obvious place of the variable's birth.

It depends: If you declare a variable outside a function, it has a "global scope", that means it can only be accessed outside of a function.
If a variable is declared inside a function, it has a "local scope" and can be used only inside that function.
(http://www.w3schools.com/php/php_variables.asp)
But it seems that the variable "cars" that you defined outside the function works for your function even without the global keyword...

Related

Define/set PHP variable

I often get PHP errors about a variable not defined. I'm also wondering what is best practice for setting session variables. Currently I'm doing this:
session_start();
if (!isset($_SESSION["myVar"]))
$_SESSION["myVar"] = "";
But this seems untidy to me. I know there is a PHP unset function, but what is the equivalent to simply set/define a variable into existence, without setting an initial value?
Php has dynamic variable allocation and typing. When a variable is first referenced within a program, memory is allocated for its use.
Meaning that unless you don't assign a value, a variable can't be declared, like say, in java.
Best way how to make sure you "declare" all your variables?
Assign them to null or empty string at the beginning of each function / method.
About session variables, I'd apply the same logic.

Notice: Undefined Variable, but PHP shouldn't require variable definitions?

I have an extension in Magento that is causing a bug in the system.log
The error message is below. It is at the return statement after the foreach statement
Notice: Undefined variable: struct
The method is
public function getFeeList($id)
{
//some code here but no statement that contains $struct
foreach($result2 as $kk=>$vv)
{
$struct[$vv['magikfees_id']]['tax_apply']=$vv['tax_apply'];
$struct[$vv['magikfees_id']]['tax_type']=$vv['tax_type'];
....
}
return $struct;
}
To my understanding is that you do not need to declare the PHP variables. So one question is
is the scope of the $struct variable in this case only in the foreach? OR
the code never gets in the foreach statement so $struct is not initialized?
is declaring it before the foreach going to resolve this issue? How can I declare it?
is the code actually working regardless of this notice?
You do not need to declare PHP variables, but you will get a notice when you don't. You can declare it as $struct = array();.
The code will work, but as $struct wasn't declared, it is likely you made a mistake (maybe a typo). PHP warns you for that by sending a notice. Although it does work without the declaration, it is recommended to declare it anyways.
No, the scope is the method getFeeList(). Once you've defined the variable you can access it later in your code in that particular method. If the code doesn't enter the foreach, the variable will be null.
Yes it will remove the notice error. You can do that by adding $struct = array(); before your foreach. Another workaround is to remove E_NOTICE from your error_reporting setting in php.ini or set ini_set() in the beginning of your code.
This particular piece of code should be working just fine even if you haven't defined the variable.
Although in PHP you are not required to define your variables it's a better coding practice to define them.

Defining constants with $GLOBALS

I want to use a global variable setup where they are all declared, initialized and use friendly syntax in PHP so I came up with this idea:
<?
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
$GLOBALS['debugger'] = 1; // set $GLOBALS['debugger'] to 1
DEFINE('DEBUGGER','$GLOBALS["debugger"]'); // friendly access to it globally
echo "1:" . DEBUGGER . ":<br>";
echo "2:" . ${DEBUGGER}. ":<br>";
echo "3:" . $GLOBALS['debugger'] . ":<br>";
if (DEBUGGER==1) {echo "DEBUG SET";}
?>
generates the following:
1:$GLOBALS["debugger"]:
Notice: Undefined variable: $GLOBALS["debugger"] in /home/tra50118/public_html/php/test.php on line 8
2::
3:1:
How can there be an error with 2: when clearly $GLOBALS["debugger"] IS defined? And then not generate a similar notice with the test at line 10?
I think what I am trying to do is to force PHP to interpret a string ($GLOBALS["debugger"]) as a variable at run time i.e. a constant variable variable
Disclaimer: I agree with the comments, globals are generally a bad idea.
That said, there's a few questions here that are worth answering, and the concept of indirection is useful, so here goes.
${'$GLOBALS["debugger"]'} is undefined. You don't include the leading '$' when using indirection. So, the correct version would be define('DEBUGGER', 'GLOBALS["debugger"]').
But, this doesn't work either. You can only access one level down via indirection. So you can access the array $GLOBALS, but you can't access keys in that array. Hence, you might use :
define('DEBUGGER', 'debugger');
${DEBUGGER};
This isn't useful, practically. You may as well just use $debugger directly, as it's been defined as a global and will be available everywhere. You may need to define global $debugger; at the start of functions however.
The reason your if statement is not causing notices is because you defined DEBUGGER to be a string. Since you aren't trying to use indirection in that line at all, it ends up reading as:
if ("$GLOBALS['debugger']"==1) {echo "DEBUG SET";}
This is clearly never true, though it is entirely valid PHP code.
I think you may have your constants crossed a bit.
DEFINE('DEBUGGER','$GLOBALS["debugger"]'); sets the constant DEBUGGER to the string $GLOBALS["debugger"].
Note that this is neither the value nor the reference, just a string.
Which causes these results:
1: Output the string $GLOBALS["debugger"]
2: Output the value of the variable named $GLOBALS["debugger"]. Note that this is the variable named "$GLOBALS["debugger"]", not the value of the key "debugger" in the array $GLOBALS. Thus a warning occurs, since that variable is undefined.
3: Output the actual value of $GLOBALS["debugger"]
Hopefully that all makes sense.
OK, thanks to all who answered. I think I get it now, I am new to PHP having come form a C++ background and was treating the define like the C++ #define and assuming it just did a string replace in the precompile/run phase.
In precis, I just wanted to use something like
DEBUGGER = 1;
instead of
$GLOBALS['debugger'] = 1;
for a whole lot of legitimate reasons; not the least of which is preventing simple typos stuffing you up. Alas, it appears this is not doable in PHP.
Thanks for the help, appreciated.
You can not use "variable variables" with any of the superglobal arrays, of which $GLOBALS is one, if you intend to do so inside an array or method. To get the behavior you would have to use $$, but this will not work as I mentioned.
Constants in php are already global, so I don't know what this would buy you from your example, or what you are going for.
Your last comparison "works" because you are setting the constant to a string, and it is possible with PHP's typecasting to compare a string to an integer. Of course it evaluates to false, which might be surprising to you, since you expected it to actually work.

Should PHP variables be initialized prior to use as an OUT function parameter?

What is the correct way to write code that calls a function that accepts a variable pointer and changes the value?
The following works, but my IDE complains that $v is an undefined variable, which it is until the function it calls sets a value:
function foo(&$bar) {
$bar = 12345;
}
foo($v);
Should I initialize $v first to satisfy my IDE? Or is there a better way to do this?
$v = NULL;
foo($v);
When passing a variable by reference to a function, you need to have a reference to the variable from the calling code. To have a reference, the variable needs to exist. To exist, the variable needs to be initialized.
I recommend setting it to a reasonable default value. If the reasonable default is null, then use null. In some cases it may be more reasonable to use '' or 0 depending on what type of value you want the variable to hold.

Changing User-Defined Global Variable Value in ExpressionEngine

Say I've got a global variable which I'm accessing inside a PHP block, which compares to a querystring... if the comparison is true I want to set the value for a global EE variable so that all the other template pages can recognise that the value is not what it normally is - is this possible, or are the global user-defined variables constants?
Thanks,
Dan
$this->EE->config->_global_vars['foo'] = 'bar';
But keep in mind that the variable may have already been parsed before you have a chance to change it, depending on where and how it's used (see EE2's parse order discusssion).
You can use the PHP $GLOBAL Superglobal Array, for such cases. Say you have written a variable in any block of a particular page as $a = 123;.
Now in the same page, but in another block, you can easily change it to something else as $GLOBALS['a'] = 456;.
Hope it helps.

Categories