Frolo321
Frolo321

Reputation: 19

How does php behave on initialized parameters?

Lets assume I have the following function:

function myTest($param = false){
echo $param;
}

And now I have the following call to the function

myTest($test);

However, $test wasnt declared yet by the moment the call is made. Will php throw an error?

I ask because I have a process where it is possible that some variables aren't instantiated before the call where they are used is made. In theory, this is okay, because I have a default behavior inside these functions handling this case (thats why Im initializing the functions parameter). However, if php throws an error in this case, then I have to build a workaround (which will be ugly ^^), but before doing so, I wanted to ask you :D

Upvotes: 1

Views: 165

Answers (1)

ALFA
ALFA

Reputation: 1744

You don't get an error, but a warning. See variable basics.

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 depending on the context in which they are used - booleans default to FALSE, integers and floats default to zero, strings (e.g. used in echo) are set as an empty string and arrays become to an empty array.

Example: Default values of uninitialized variables

<?php
// Unset AND unreferenced (no use context) variable; outputs NULL
var_dump($unset_var);

// Boolean usage; outputs 'false' (See ternary operators for more on this syntax)
echo($unset_bool ? "true\n" : "false\n");

// String usage; outputs 'string(3) "abc"'
$unset_str .= 'abc';
var_dump($unset_str);

// Integer usage; outputs 'int(25)'
$unset_int += 25; // 0 + 25 => 25
var_dump($unset_int);

// Float/double usage; outputs 'float(1.25)'
$unset_float += 1.25;
var_dump($unset_float);

// Array usage; outputs array(1) {  [3]=>  string(3) "def" }
$unset_arr[3] = "def"; // array() + array(3 => "def") => array(3 => "def")
var_dump($unset_arr);

// 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" }
$unset_obj->foo = 'bar';
var_dump($unset_obj);
?>

Upvotes: 2

Related Questions