douhe1864 2018-12-11 10:45
浏览 79
已采纳

(二元)铸造实际上做了什么以及为什么不应该依赖它?

I'm using PHP 7.2.12

I come across following statement from the Type Casting section of PHP Manual :

(binary) casting and b prefix forward support was added in PHP 5.2.1. Note that the (binary) cast is essential the same as (string), but it should not be relied upon.

I didn't understand the above text thoroughly. Someone please explain to me with good explanation.

I studied the following code examples given in PHP Manual on the same page :

<?php
$binary = (binary) $string;
var_dump($binary);
$binary = b"binary string";
var_dump($binary);
?>

Output :

Notice: Undefined variable: string in ..... on line 2
string(0) ""
string(13) "binary string"

If you look at the output above I got the same strings even after the casting to binary. So, what conversion job does binary casting actually do?

Why the binary casting should not be relied upon?

Also, explain to me on what types the binary casting can be done? I mean it's legal.

Nowhere in the PHP manual, there is any explanation or justification in this regard.

Someone please help me out on this by guiding me in a right direction.

  • 写回答

1条回答 默认 最新

  • duandian8110 2018-12-11 10:52
    关注

    PHP had Big Plans™ for PHP 6, where strings would finally become Unicode strings. To illustrate what that means, the current PHP behaviour:

    $str = '漢字';
    echo $str[0];
    // ?
    

    In PHP 6, this would have output "漢" instead of a broken ?. In other words, strings are encoding and character aware, instead of dumb byte arrays. (To output "漢" in current PHP versions, you need something like mb_substr($str, 0, 1, 'UTF-8').)

    To keep the old dumb-byte-array behaviour, you could prefix your strings with b'漢字' and you could cast Unicode strings to dumb byte arrays using (binary). This was all added to PHP 5 in preparation for PHP 6, so you could start updating your code in advance.

    Well, except PHP 6 never happened, and b'' prefixes and (binary) casts still don't do anything to this date.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 视频编码 十六进制问题
  • ¥15 Xsheii7我安装这个文件的时候跳出来另一个文件已锁定文件的无一部分进程无法访问。这个该怎么解决
  • ¥15 unity terrain打包后地形错位,跟建筑不在同一个位置,怎么办
  • ¥15 FileNotFoundError 解决方案
  • ¥15 uniapp实现如下图的图表功能
  • ¥15 u-subsection如何修改相邻两个节点样式
  • ¥30 vs2010开发 WFP(windows filtering platform)
  • ¥15 服务端控制goose报文控制块的发布问题
  • ¥15 学习指导与未来导向啊
  • ¥15 求多普勒频移瞬时表达式