0

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?

2
  • 1
    You mean be a string and an int at the same time? No. Definitely not. Commented Jan 17, 2012 at 8:05
  • Without having checked the source code I assume PHP uses some kind of representation cache, so that if a variable is accessed as a string, the string representation is cached and if, later on, it is accessed as an integer, the variable will have both representations cached. But short of that, I can't see how one variable having more than one data type would manifest itself. Commented Jan 17, 2012 at 8:08

5 Answers 5

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

No. PHP just interprets the value however it likes, since it's weakly-typed.

Comments

0

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.

Comments

0

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.

1 Comment

No, the type the variable holds is an array or object at that time, and still only one type.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.