在PHP中指定类的对象类型的方法

Ced*_*ric 12 php oop types

有没有办法在PHP中指定对象的属性类型?例如,我有类似的东西:

class foo{
 public bar $megacool;//this is a 'bar' object
 public bar2 $megasupercool;//this is a 'bar2' object
}


class bar{...}
class bar2{...}
Run Code Online (Sandbox Code Playgroud)

如果没有,你知道是否有可能在PHP的未来版本之一,有一天?

Gor*_*don 12

除了已经提到的TypeHinting之外,您还可以记录该属性,例如

class FileFinder
{
    /**
     * The Query to run against the FileSystem
     * @var \FileFinder\FileQuery;
     */
    protected $_query;

    /**
     * Contains the result of the FileQuery
     * @var Array
     */
    protected $_result;

 // ... more code
Run Code Online (Sandbox Code Playgroud)

@var annotation将有助于一些IDE提供代码帮助.


Pek*_*ica 6

您正在寻找的是名为Type Hinting,并且在PHP 5/5.1中部分可用于函数声明,但不是您想要在类定义中使用它的方式.

这有效:

<?php
class MyClass
{
   public function test(OtherClass $otherclass) {
        echo $otherclass->var;
    }
Run Code Online (Sandbox Code Playgroud)

但这不是:

class MyClass
  {
    public OtherClass $otherclass;
Run Code Online (Sandbox Code Playgroud)

我不认为这是未来的计划,至少我不知道它是否计划用于PHP 6.

但是,您可以使用对象中的getter和setter函数强制执行自己的类型检查规则.不过,它不会像现在一样强劲OtherClass $otherclass.

关于类型提示的PHP手册