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.

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

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效