略微加速

略速 - 互联网笔记

PHP b前缀字符串/binary类型强制转换

2020-08-05 15:31:01 leiting (260阅读)

标签 PHP

看PHP文档《类型转换的判别》一章:

http://www.lvesu.com/blog/php/language.types.type-juggling.php

发现个新鲜玩意,b前缀字符串,官网文档的描述:

1596612141123.jpg

还举了个例子:

1596612191801.jpg

什么鬼……看不明白

stackoverflow上搜一下:


Binary strings were introduced in PHP 5.2.1 but were expected to become effective only starting from PHP 6. It was an attempt to distinguish between Unicode and binary strings. The former being the new string format, the latter being the current format but changed to "b" notation.

As you may know, PHP 6 had been abandoned and string format didn't change. The "b" notation is just a relic from that era.

'foobar' === b'foobar'; // true

So nowadays (PHP 5 and 7), binary string is the only string format. The character encoding (which can be multibyte) is managed at the "upper level", by your text editor, web browser, etc. You can consider a binary string to be a string consisting of the full 0-255 range of byte values.

A string with nonprintable characters and such, can be manipulated in PHP as any other string, but you'll get garbage displaying it. Also some characters have special meaning: \0 marks string termination in C and SQL, there are control characters, etc. So as soon as you use them outside of PHP you are likely to encounter troubles.

For example, random_bytes() produces such strings.


机翻一下:


二进制字符串在PHP 5.2.1中引入,但预期仅从PHP 6开始才有效。这是试图区分Unicode字符串和二进制字符串。前者是新的字符串格式,后者是当前格式,但更改为“ b”表示法。

如您所知,PHP 6已被放弃,字符串格式没有改变。“ b”符号只是那个时代的遗物。

'foobar' === b'foobar'; // true

因此,如今(PHP 5和7),二进制字符串是唯一的字符串格式。字符编码(可以是多字节)可以通过文本编辑器,Web浏览器等在“较高级别”上进行管理。您可以将二进制字符串视为包含0-255字节值范围的字符串。

带有不可打印字符等的字符串可以像其他任何字符串一样在PHP中进行处理,但是显示时会出现乱码。还有一些字符具有特殊含义:\0在C和SQL中标记字符串终止,还有控制字符等。因此,一旦在PHP之外使用它们,您很可能会遇到麻烦。

例如,random_bytes()产生这样的字符串。


意思就是废弃的特性其实没啥用……现在的PHP其实默认就是b前缀的字符串


北京半月雨文化科技有限公司.版权所有 京ICP备12026184号