Reputation: 16152
I'm guessing this has been asked already. I know in php you can change the datatype of a variable as in this example.
$var = '3';
if (is_string($var))
echo "variable is now string <br />";
$var = $var+1;
if (is_int($var))
echo "variable is now integer <br />";
However can a variable hold more than one data type at a single point in time?
Upvotes: 0
Views: 2616
Reputation: 27876
Yes. A variable can be a holder for multiple datatypes and values at a single point in time if is an array or an object.
Upvotes: 0
Reputation: 157981
An array can contain many items of whatever types.
$array = array("string",1,false,fopen(__FILE__,"r"));
var_dump($array);
But being a variable itself, it can be of just one type - array
.
though I see no sense in the question or imagine any reason to ask it at all. what's the point in having one variable of several types at once? May be it is just unclearly asked.
Upvotes: 1
Reputation: 785971
If you add var_dump like this in your code:
$var = '3';
var_dump($var);
if (is_string($var))
echo "variable is now string <br />\n";
$var = $var+1;
var_dump($var);
if (is_int($var))
echo "variable is now integer <br />\n";
Your output will be:
string(1) "3"
variable is now string <br />
int(4)
variable is now integer <br />
Which indicates a simple rule that PHP lets you use a variable in whatever way you like and changes the data type it repsents as you use in your code.
Upvotes: 0
Reputation: 106077
No. A variable can only hold a single value at a time. Of course, that value could be an array or an object, which itself could hold multiple values, but the variable itself is still a reference to a single object.
Upvotes: 0
Reputation: 799250
No. PHP just interprets the value however it likes, since it's weakly-typed.
Upvotes: 0