简体   繁体   中英

Can a php variable hold multiple data types at once?

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?

不会。PHP只是解释它喜欢的值,因为它的类型很弱。

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.

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM