应该使用Php string cast vs strval函数?

时间:2022-06-01 16:49:07

What is the difference between doing a string cast and strval in php ?

在php中执行字符串转换和strval有什么区别?

  1. strval($value);

  2. (string)$value;

3 个解决方案

#1


19  

http://www.php.net/manual/en/language.types.string.php#language.types.string.casting

A value can be converted to a string using the (string) cast or the strval() function.

可以使用(string)强制转换或strval()函数将值转换为字符串。

Looks the same to me.

看起来和我一样。

#2


5  

One is a function call, the other one is an internal typecast. Without having checked, I'd guess the latter one is faster by few cycles, but shouldn't really make a difference.

一个是函数调用,另一个是内部类型转换。如果没有经过检查,我猜测后者会在几个周期内更快,但不应该真正有所作为。

#3


3  

They are generally interchangeable because PHP uses automatic type conversion and a variable's type is determined by the context in which the variable is used.

它们通常是可互换的,因为PHP使用自动类型转换,变量的类型由使用变量的上下文决定。

Some differences are that strval($var) will return the string value of $var while (string) $var is explicitly converting the "type" of $var during evaluation.

一些差异是strval($ var)将返回$ var的字符串值而(string)$ var在评估期间显式转换$ var的“type”。

Also, from the manual, for strval() $var "may be any scalar type or an object that implements the __toString method. You cannot use strval() on arrays or on objects that do not implement the __toString method."

另外,从手册中,对于strval()$ var,可以是任何标量类型或实现__toString方法的对象。不能对数组或不实现__toString方法的对象使用strval()。“

As mentioned by @Lars (string) is generally faster.

正如@Lars所提到的(字符串)通常更快。

#1


19  

http://www.php.net/manual/en/language.types.string.php#language.types.string.casting

A value can be converted to a string using the (string) cast or the strval() function.

可以使用(string)强制转换或strval()函数将值转换为字符串。

Looks the same to me.

看起来和我一样。

#2


5  

One is a function call, the other one is an internal typecast. Without having checked, I'd guess the latter one is faster by few cycles, but shouldn't really make a difference.

一个是函数调用,另一个是内部类型转换。如果没有经过检查,我猜测后者会在几个周期内更快,但不应该真正有所作为。

#3


3  

They are generally interchangeable because PHP uses automatic type conversion and a variable's type is determined by the context in which the variable is used.

它们通常是可互换的,因为PHP使用自动类型转换,变量的类型由使用变量的上下文决定。

Some differences are that strval($var) will return the string value of $var while (string) $var is explicitly converting the "type" of $var during evaluation.

一些差异是strval($ var)将返回$ var的字符串值而(string)$ var在评估期间显式转换$ var的“type”。

Also, from the manual, for strval() $var "may be any scalar type or an object that implements the __toString method. You cannot use strval() on arrays or on objects that do not implement the __toString method."

另外,从手册中,对于strval()$ var,可以是任何标量类型或实现__toString方法的对象。不能对数组或不实现__toString方法的对象使用strval()。“

As mentioned by @Lars (string) is generally faster.

正如@Lars所提到的(字符串)通常更快。