In Java when I declare a variable int A; by default it assigns 0 to the variable A. But in PHP if I declare a variable as $A the default value of it sets as null. Instead of assigning it as $A=0; are there any ways available to set a default value as 0 for variable $A, as I did in Java?
-
2PHP does not use variable types, so you will have to do $A=0 when you declare $ADeepanshu Goyal– Deepanshu Goyal2013-10-05 06:57:37 +00:00Commented Oct 5, 2013 at 6:57
-
@Deep PHP has types, but they're inferred instead of declared.deceze– deceze ♦2013-10-05 07:03:10 +00:00Commented Oct 5, 2013 at 7:03
-
2@Hiru Don't try to port habits from other languages to PHP. PHP isn't Java and Java isn't PHP. Nobody uses "implicit type default values" in PHP the way you are trying to do.deceze– deceze ♦2013-10-05 07:05:56 +00:00Commented Oct 5, 2013 at 7:05
5 Answers
You can set its type. Since you don't wana initialize to 0, setting type to integer will do that for you.
<?php
settype($foo, "integer");
echo $foo;
?>
6 Comments
$foo = (int)null. If $foo already existed before, who knows what you're going to get?$foo = 0; except more verbose and error-prone, so why would you want to use it?$foo as an integer type (i.e. settype($foo, "integer"); $foo = "bar"; won't even throw a warning).Since you do not explicitly declare variables to be of a certain type, but PHP does type inference instead, there's no way to make an integer without assigning an integer value. In Java you can make a default value by declaring the type of a variable, in PHP you declare the type of a variable by assigning a value of that type to it. There may be several ways how to get an integer value of 0, but none is as straight forward as using a literal 0.
Comments
you can do like this, following will help you
echo (int)$A;
You can use php settype which set the type of a variable
<?php
settype($var,'integer');
echo $var;
?>
Refer php settype