|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2008-06-08 12:13 UTC] chrisvroberts at gmail dot com
Description: ------------ On "http://www.php.net/manual/en/language.variables.php", it says: "It is not necessary to initialize variables in PHP however it is a very good practice. Uninitialized variables have a default value of their type - FALSE, zero, empty string or an empty array." However, I was unable to find in the documentation how to define a variable and specify it's type without assigning a value to it. When a variable is declared and not initialized, which of the values described above would the variable take. If it is used in a context which specifies say boolean, then value would be FALSE but if it is used in an overloaded context, which value would it take and is there a precedence? Is this implementaitn rather than language specific? If it is possible to specify a variables type without assigning to it, perhaps this should be described in the documentation in order to put the above quote into context? PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2026 The PHP GroupAll rights reserved. |
Last updated: Wed Oct 07 23:00:01 2026 UTC |
PHP is not a fully typed language, because of this variables' types are only used depending on the context in which they are referred to. I have a rather lengthy example to explain this (see below) but I'll try to trim that down before it's committed. // Example: <?php // Unset variable; outputs NULL var_dump($unset_var); // Boolean usage; outputs 'false' echo("Boolean\n"); // See ternary operators for more on this syntax echo($unset_bool ? "true\n" : "false\n"); echo("\n"); // String usage; outputs 'string(3) "abc"' echo("String\n"); $unset_str .= 'abc'; var_dump($unset_str); echo("\n"); // Integer usage; outputs 'int(25)' echo("Integer\n"); $unset_int += 25; // 0 + 25 => 25 var_dump($unset_int); echo("\n"); // Float/double usage; outputs 'float(1.25)' echo("Float\n"); $unset_float += 1.25; var_dump($unset_float); echo("\n"); // Array usage; outputs array(1) { [3]=> string(3) "def" } echo("Array\n"); $unset_arr[3] = "def"; // array() + array(3 => "def") => array(3 => "def") var_dump($unset_arr); echo("\n"); // Object usage; creates new stdClass object (see http://www.php.net/manual/en/reserved.classes.php) // Outputs: // object(stdClass)#1 (1) { // ["foo"]=> // string(3) "bar" // } echo("Object\n"); $unset_obj->foo = 'bar'; var_dump($unset_obj); echo("\n"); ?>