doutangdan3588 2008-12-24 06:57
浏览 224
已采纳

在PHP中声明变量类型?

I was trying to get my Netbeans to autocomplete with PHP, and I learned that this code is valid in PHP:

function blah(Bur $bur) {}

A couple of questions:

  1. Does this actually impose any limits on what type of variable I can pass to the blah method?
  2. If this is just to help the IDE, that's fine with me. How can I declare the type of a variable in PHP if I'm not in a function?
  • 写回答

5条回答 默认 最新

  • dongsheng8158 2008-12-24 19:36
    关注

    This type-hinting only works for validating function arguments; you can't declare that a PHP variable must always be of a certain type. This means that in your example, $bur must be of type Bur when "blah" is called, but $bur could be reassigned to a non-Bur value inside the function.

    Type-hinting only works for class or interface names; you can't declare that an argument must be an integer, for example.

    One annoying aspect of PHP's type-hinting, which is different from Java's, is that NULL values aren't allowed. So if you want the option of passing NULL instead of an object, you must remove the type-hint and do something like this at the top of the function:

    assert('$bur === NULL || $bur instanceof Bur');
    

    EDIT: This last paragraph doesn't apply since PHP 5.1; you can now use NULL as a default value, even with a type hint.

    EDIT: You can also install the SPL Type Handling extension, which gives you wrapper types for strings, ints, floats, booleans, and enums.

    EDIT: You can also use "array" since PHP 5.1, and "callable" since PHP 5.4.

    EDIT: You can also use "string", "int", "float" and "bool" since PHP 7.0.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器