PHP doesn't have an explicit statement to initialise variables, like Javascript's var. PHP variables get initialised when they're first assigned to. It's a design choice, for better or worse. To create a variable you always have to assign something to it. Since a variable must have some value and PHP's value for "nothing" is null, you want:
$variable = null;
(Alternative ways to create variables exists, like references, e.g.: parse_str(, but let's leave that aside.)bar); var_dump($bar);
The var statement exists in Javascript to determine scope; Javascript has nested scopes and needs an explicit initialisation to determine what a variable's scope is. Scoping in PHP works differently and doesn't have that ambiguity, hence such a separate statement isn't necessary. Originally PHP also liked implicit globals a lot (a terrible idea in hindsight), which somewhat clashes with the idea of explicit initialisation statements in the first place.
var $var;(a variable declared, but without a value)
That is an incomplete/incorrect quote, it should be "a variable declared but without a value in a class", since that's the only place the var keyword can be used.
As an example, Python also uses initialisation-by-assignment, and also has nested scope. It uses a different approach to resolve this:
foo = 42
def bar():
foo = 69
def baz():
nonlocal foo
foo = 2
The rule in Python is, that a variable is local to a function if any assignment is done to the variable inside the function. So the foo = 69 creates a new local variable inside bar here. To allow assignment to the variable from an inherited scope, the nonlocal or global keyword must be used to explicitly denote that variable as inherited. foo = 2 here reassigns foo = 69, but neither reassigns foo = 42.
PHP doesn't have an explicit statement to initialise variables, like Javascript's var. PHP variables get initialised when they're first assigned to. It's a design choice, for better or worse. To create a variable you always have to assign something to it. Since a variable must have some value and PHP's value for "nothing" is null, you want:
$variable = null;
(Alternative ways to create variables exists, like references, e.g.: parse_str(, but let's leave that aside.)bar); var_dump($bar);
The var statement exists in Javascript to determine scope; Javascript has nested scopes and needs an explicit initialisation to determine what a variable's scope is. Scoping in PHP works differently and doesn't have that ambiguity, hence such a separate statement isn't necessary. Originally PHP also liked implicit globals a lot (a terrible idea in hindsight), which somewhat clashes with the idea of explicit initialisation statements in the first place.
var $var;(a variable declared, but without a value)
That is an incomplete/incorrect quote, it should be "a variable declared but without a value in a class", since that's the only place the var keyword can be used.
As an example, Python also uses initialisation-by-assignment, and also has nested scope. It uses a different approach to resolve this:
foo = 42
def bar():
foo = 69
def baz():
nonlocal foo
foo = 2
The rule in Python is, that a variable is local to a function if any assignment is done to the variable inside the function. So the foo = 69 creates a new local variable inside bar here. To allow assignment to the variable from an inherited scope, the nonlocal or global keyword must be used to explicitly denote that variable as inherited. foo = 2 here reassigns foo = 69, but neither reassigns foo = 42.
There is no var keyword which works the same way as in javascript. From w3schools:
Note: Unlike other programming languages, PHP has no command for declaring a variable. It is created the moment you first assign a value to it.
Your other question:
If it's not possible, is there any logical explanation why it wasn't implemented in PHP?
One logical explanation could be that in PHP all variables start with a $ symbol. So PHP immediately knows when something is a variable and not a function or keyword, without the need for a declaration.
In fact, javascript code also works without declarations, but here, they are still recommended in most cases.
If you want to declare a variable and set its value to null in PHP, just use:
$myVar = null;
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.
The sample code is (almost) valid (it's just missing a few $ signs.)
class foo
{
// these will default to null
public $bar;
protected $baz;
private $bas;
// perfectly valid initializer to "string" value
public $var1 = "Test"; //String
// perfectly valid initializer to "float" value
public $var2 = 1.23; //Numericvalue
// perfectly valid initializer to "array" value
// (array() is a language construct/literal, not a function)
public $var3 = array(1,2,3);
}
So, the book your code comes from is definitely in error.
No, this is an error. Defining:
public var1="Test"; //String
Will give you:
Parse error: syntax error, unexpected T_STRING, expecting T_VARIABLE
For details, see http://codepad.org/meMrSmfA.
Depends on your design:
- Are you setting it as an Object in case of error? Use
NULL. - Are you setting it to
truein case of error? Usefalse. - Are you setting it as a number of some sort in case of error? Use
0. - Are you setting it to a string to describe the error? Use
''.
A better way to indicate errors would be throwing Exceptions though, rather than setting a variable and determine the error according to it.
There is no canonical answer to this question. As long as you use one of these semaphores consistently, you can use anything you want. Because PHP is loosely-typed, all of these values are "falsy" and can be evaluated in a boolean comparison as FALSE.
That said, there is more of a difference between the empty string and the others, so I'd stick with NULLs and FALSEs in this sort of scenario.
$test = ' ' is not empty. From the details in the documentation:
The following things are considered to be empty:
- "" (an empty string)
- 0 (0 as an integer)
- 0.0 (0 as a float)
- "0" (0 as a string)
- NULL
- FALSE
- array() (an empty array)
- var $var; (a variable declared, but without a value in a class)
If you want to test if $test is only white space characters, see these questions:
If string only contains spaces?
How to check if there are only spaces in string in PHP?
Trim the value before checking it.
It is important to trim before checking it because empty only checks variables and not the value you're passing in.
$test = trim(' ');
if (empty($test)) { /* ... */ }
echo $test;
In PHP, a constant can be defined, which would then not have a $, but a variable must have one. However, this is NOT a variable, and is not a substitute for a variable. Constants are intended to be defined exactly once and not changed throughout the lifetime of the script.
define('a', 'some value for a');
Additionally, you cannot interpolate the value of a constant inside a double-quoted or HEREDOC string:
$a = "variable a"
define('a', 'constant a');
echo "A string containing $a";
// "A string containing variable a";
// Can't do it with the constant
echo "A string containing a";
// "A string containing a";
Finally, PHP may issue a notice for an Use of undefined constant a - assumed 'a' and interpret it as a mistakenly unquoted string "a". Look in your error log to see if that is happening. In that case, "a" == TRUE is valid, since the string "a" is non-empty and it is compared loosely to the boolean TRUE.
echo a == TRUE ? 'true' : 'false';
// Prints true
// PHP Notice: Use of undefined constant a - assumed 'a'
With this code:
if ($a != 0 && a == true) {
...
}
You're not getting any error because you (or someone else) have told PHP to not report any errors, warnings or notices with that code. You set error reporting to a higher level and you will get a notice:
Notice: Use of undefined constant a - assumed 'a' in ...
Which will mean that a is read as a constant with a value of "a". This is not what you're actually looking for I guess:
if ($a != 0 && "a" == true) {
...
}
The second part "a" == true will always be true, so this is actually like so:
if ($a != 0) {
...
}
As it's not your code, one can only assume that this was not intended by the original author.
So: Variables in PHP always start with the dollar sign $. Everything else is not a variable.
You can initialize a variable like this:
$result = NULL;
You can try using any of the following:
{
$result = false;
if (empty($name) || empty($email) || empty($password) || ($confirm_password)) {
$result = true;
}
return $result;
}
// or
{
if (empty($name) || empty($email) || empty($password) || ($confirm_password)) {
return true;
}
return false;
}
// or
{
return (empty($name) || empty($email) || empty($password) || ($confirm_password));
}
All these constructs produce the same result.
You don't declare variables in PHP, you define them.
There's no need for $result; and it actually means "read the value of the variable $result and then do nothing with it" - which will give you an undefined variable error if $result isn't defined (which, in your case, it is).
What you have to do instead is initialize $result to some value, or leave it out completely:
$result = false;
For example.
Your code can be greatly simplified by just using assigment:
$result = empty($name) || empty($email) || empty($password) || ($confirm_password);
No need for the if. And you can actually ditch the $result variable entirely:
function emptyInputSignup($name, $email, $password, $confirm_password) {
return empty($name) || empty($email) || empty($password) || ($confirm_password);
}
How you are declaring is perfectly alright and proper way.
$test = "";
or
$test = null;
these both are proper ways for declaring empty variables. for more info please visit http://php.net/manual/en/language.types.null.php
You need to declare variables before echoing them out. An example is here:
<?php
$var = "test";
echo $var; // it will echo out test
?>
And trying to echo out a variable this way will generate an error:
<?php
echo $var; // it will generate error
$var = "test";
?>
In addition, you can declare variables in another file and can include that file to echo out the variable somewhere. Remember to include the file first and then call it.
Example vars.php:
<?php
// define vars
$var1 = "Test 1";
$var2 = "Test 2";
?>
Now in another file, include vars.php first and then call the variable:
<?php
require_once"vars.php";
echo $var1;
?>