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

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.

Related

Getting Undefined variable: type in laravel

I am getting this message
While trying to load a page. And its indicating to this line of code
return view('admin/vehicle-categories/index',compact('categories','level','parent_categories','type','parent_id'));
}
How can I solve this?
This was a breaking change introduced in PHP 7.2. Previously you could compact a named variable that was not yet defined. After 7.2 you must define the variable previous to adding to the compact method.
Broke a lot of code for us as well.
The fix is to simply define the variable before the compact statement, even if null. Be careful if going through a branch/if-check that you define it for certain:
$type == null // or value

Is it necessary to Initialize / Declare variable in 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...

PHP, an odd variable scope?

This more a question about the why then 'how-to', yet it has been annoying me for some days now. Currently I am doing some work with CodeIgniter and going back to PHP temporarily from Ruby, bugs me about the following scoping magic.
<?php $query = $this->db->get('articles', 2);
if ($query->num_rows() > 0)
{
foreach ($query->result_array() as $row)
{
$data[] = $row; # <-- first appearance here
}
return $data; # <--- :S what?!
}
As you can see, I am not exactly a PHP guru, yet the idea of local scope bugs me that outside the foreach loop the variable is 'available'. So I tried this out inside a view:
<?php
if($a==1)
{
$b = 2;
}
echo $b;
?>
Which result in an error message:
Message: Undefined variable: b
The PHP manual tells about the local scoping, yet I am still wondering why this happens and if there are special rules I do not know about. And it scares me :)
Thanks for sharing ideas,
Only functions create a new local scope. Curly braces by themselves do not. Curly braces are just an auxillary construct for other language structures (if, while or foreach).
And whereever you access any variable in a local scope doesn't matter. The local scope is an implicit dictionary behind the scenes (see get_defined_vars). You might get a debug notice by accessing previously undefined variables, but that's about it.
In your specific example it seems, you are even just operating in the global scope.
foreach does not create any variable scope in PHP so it is natural if variable is available outside foreach
for the second question the $a is not equal to the 1 hence $b is not initialized and throw notice when you access outside. If you assign value 1 to $a and test it you will wonder the notices will gone.
Here is nothing like scope.
See: http://php.net/manual/en/language.variables.scope.php
In php curly braces don't necessarily define a new scope for variables. (your first example)
In your 2nd example, $b is only set on a specific condition. So it is possible to be 'undefined' if this condition is not met.
Shyam, you are using a scripting language, not C++. It is typical for scripting languages like PHP or JavaScript not to have different scopes for each code block. Instead there is one scope for the whole function. This is actually quite handy if you consider your first example, but you obviously need to be careful as can be seen in your second one.
is $a equals to 1? If not $b=2 will never be evaluated!
Actually your first method should be giving you an error too.
You're using a variable that hasn't been declared as an array. I can't understand why you didn't get an error for that.
PHP doesn't have block scope, so whether it's inside IF or FOREACH is irrelevant. If it's available inside the method, you can use it inside the method.

What is the meaning of this structure in open cart programming "${$module['code']};"?

Hi I am new to opencart and currently facing one issue that not able to identify why it is coming
"Notice: Undefined variable: dailydeal in ~/template/common/column_right.tpl on line 3"
At line no 3 in this file the code written is as follows:
<?php echo ${$module['code']}; ?>
Can any one tell me the what is meaning of this syntax. or how I can solve this issue.
Thanks a lot in advance.
That's a variable variable, from your error I can tell that:
echo $module['code']; // dailydeal
The ${$module['code']} is the equivalent of $dailydeal (the variable content).
To avoid OpenCart throwing notices you can either lower your error reporting level, like this:
error_reporting(E_ALL & ~E_NOTICE);
Or just fix the notice altogether, by adding an isset() check:
if (isset(${$module['code']})) {
// do stuff
}
see this article variable variables there is written
In order to use variable variables
with arrays, you have to resolve an
ambiguity problem. That is, if you
write $$a1 then the parser needs to
know if you meant to use $a1 as a
variable, or if you wanted $$a as the
variable and then the 1 index from
that variable. The syntax for
resolving this ambiguity is: ${$a1}
for the first case and ${$a}1 for
the second.
also read
language variable

PHP: just saying $someVariable; inside a function - does this do anything

I'm working on some PHP code (that I didn't write). Here and there inside functions there's stuff like this:
$foo;
if ($someCondition) {
$foo="some value";
}
return $foo;
Just checking: that first $foo; on a line by itself - it has no effect whatsoever, right?
This is debug code left over from PHP3 or PHP4. These versions generated an E_NOTICE for just mentioning a variable (it was implicitly a read access):
$undef; // E_NOTICE
PHP5 however does not treat it as variable access anymore. So it goes ignored.
PHP3: Warning: Uninitialized variable or array index or property (undef)
PHP4: Notice: Undefined variable: undef
PHP5: silence
Your right. Maybe original developer come from another language and "declare" used vars.
Another way to write this code snippet is
if ($someCondition) {
return "some value";
}
return null;
It would have some impact if it were:
global $foo;
But in the form you posted, it is irrelevant.
Right, no need for it at all. Some languages require a variable to be declared, not PHP.
In PHP, you can even concatenate into an undeclared variable. PHP is the loose hipster of the programming world. Anything goes, man.
I would guess it's lazy instantiation. I'd change the line to $foo = "", which should have the same effect;
I wonder if they think that its the equivalent to defining a variable to prevent errors when strict error reporting is enabled - although it actually doesn't (define the variable) when its written like that

Categories