strval 和转换为字符串 (string) $var 之间有什么特别的区别吗

Is there any particular difference between strval and casting to string like (string) $var

这两种方法似乎没有区别,因为 var_dump returns 使用这两种方法的结果相同。

简单示例:

// integer 
$var = 3;

方法和输出:

var_dump($var);         // ouput: int(3)
var_dump((string) $var);  // string(1) "3"
var_dump(strval($var));  // string(1) "3" 

如您所见,案例 2 和案例 3 returns 一个例外的字符串。

你怎么看?

最大的区别在于函数(任何函数)都会产生一些开销。这是一个微不足道的数量,所以在大多数情况下,这个讨论比其他任何事情都更具学术性。 Gerton 的 link 证明它的速度较慢,但​​你不太可能注意到正常执行中的差距,因为他 运行 函数 100 万次 得到 0.7s 差距(他使用的是 PHP 5.2,而 PHP 7 可能会使差距更小)。 Consider this article on function execution time

The second tip is that PHP is fast, believe me. For what you ask it to do, the way it does the job and the tools it represents to you : it is fast, efficient, reliable. There is not that much room to optimize PHP scripts, at least not as if you were using lower level language like C. The main trick is to optimize what is repeated : loops. If you use a profiler showing you the hot path of you script, you'll happen to find that it is likely to be located into loops. That's the same when we, as contributors, optimize PHP itself : we won't bother optimizing a part of code a few users will trigger, but better optimize the hot path : variable accesses, engine function calls, etc... Because in here, the very little micro-second earned will translate to final milli-seconds or even seconds, as such code is run tons of times (usually involving in loops). Except foreach(), in PHP, loops are the same and lead to the same OPCode. Turning a PHP's while loop into a for loop is both useless and silly. Once more : profiling will tell you that.