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.

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

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?