为什么和什么时候应该在PHP中输入变量?

时间:2022-09-20 10:38:19

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?

在PHP中定义字符串变量的第一种方法有优势吗?

2 个解决方案

#1


3  

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

您的“类型设置”代码实际上并没有完成任何事情。

(type) $var = literal does this:

$var = literal:

  1. Assign literal value to $var with the literal value's native type.
  2. 将文字值指定为$var,并使用文字值的本机类型。
  3. "Return" (as an expression) the value of $var cast to the desired type.
  4. “Return”(作为表达式)$var转换为所需类型的值。

The type of $var remains unchanged.

$var的类型保持不变。

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;

但是,强制一个变量为特定类型是有用的,例如:$intvar = (int) $var;

#2


1  

Is there an advantage over the first way

第一种方式有优势吗?

yes. second one is more concise.

是的。第二点更简洁。

What are the advantages of typecasting variables in PHP

在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.

将其转换为预期类型。但你很少需要用到字符串。有了变量定义,你根本就不需要它。

#1


3  

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

您的“类型设置”代码实际上并没有完成任何事情。

(type) $var = literal does this:

$var = literal:

  1. Assign literal value to $var with the literal value's native type.
  2. 将文字值指定为$var,并使用文字值的本机类型。
  3. "Return" (as an expression) the value of $var cast to the desired type.
  4. “Return”(作为表达式)$var转换为所需类型的值。

The type of $var remains unchanged.

$var的类型保持不变。

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;

但是,强制一个变量为特定类型是有用的,例如:$intvar = (int) $var;

#2


1  

Is there an advantage over the first way

第一种方式有优势吗?

yes. second one is more concise.

是的。第二点更简洁。

What are the advantages of typecasting variables in PHP

在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.

将其转换为预期类型。但你很少需要用到字符串。有了变量定义,你根本就不需要它。