为什么以及何时应该在PHP中对变量进行类型转换

问题描述:

Given this declaration:

(string)$my_string = 'Hello world';

*vs*

$my_string = 'Hello world';

or*

 (int)$my_int = 1;


 $my_int = 1;

Is there an advantage over the first way of defining a string variable in PHP?

鉴于此声明: p>

 (string)$ my_string =  'Hello world'; 
  code>  pre> 
 
 

* vs em> * strong> p>

   $ my_string ='Hello world'; 
  code>  pre> 
 
 

或* strong> p>

 (int)$ my_int = 1; 
 
 
 $ my_int = 1; 
  code>  pre> 
 
 

第一种定义字符串变量的方法是否有优势 用PHP? p> div>

Your "typecasting" code doesn't actually accomplish anything.

(type) $var = literal does this:

  1. Assign literal value to $var with the literal value's native type.
  2. "Return" (as an expression) the value of $var cast to the desired type.

The type of $var remains unchanged.

For example:

var_dump((string) $s = 1);
var_dump($s);

Output is:

string(1) "1"
int(1)

So there is no point to this syntax. Typecasting with a literal is almost certainly pointless.

However it can be useful to force a variable to be a certain type, for example: $intvar = (int) $var;

Is there an advantage over the first way

yes. second one is more concise.

What are the advantages of typecasting variables in PHP

casting it to the expected type.
you seldom need it with strings though.
and with variable definitions you don't need it at all.