I am fairly new to PHP (less than a year), and to improve my development environment, I recently started using NetBeans IDE.
A warning keeps popping up everywhere stating that “Variable might not have been initialized”.
I’ll give an example of a variable that results in this hint/warning:
$start = $per_page * $page;
My question is: How can I initialize a PHP variable? Also, how important is it that a variable is initialized in PHP?
I appreciate any advice you can provide.
Note: I tried to place the following code above my variable, to no avail.
$start = '';
Advertisement
Answer
$foo ='';
That’s how you initialize a variable. So you are correct.
$start = $per_page * $page;
For the above code, if one of the variables on the right side of the equation is not being initialized anywhere in the code, your IDE will complain thinking that they might be null. You might want to initialize them on separate lines to see if you will get the same warning.
Unlike for Java- and C#-like languages, in which you get lot of null pointer exceptions, the same thing doesn’t count for PHP. PHP is weakly-typed language, so you won’t get any null pointer exceptions.
$start = $notinitiliazedvar;
This will basically have a default value.
<?php class Foo{ public $name; public $id; function __construct(){ } public function toString(){ return "{$this->name}, {$this->id}"; } } $f = new Foo(); $f->name = $test; echo $f->name; ?>
You won’t get any output with this code. So it’s OK. It’s just your IDE being paranoid.
$test = 1; echo $test; $test = "test"; echo $test;