【问题标题】:way to specify class's type of an object in PHP在 PHP 中指定类的对象类型的方法
【发布时间】:2011-03-11 01:19:22
【问题描述】:

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

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


class bar{...}
class bar2{...}

如果没有,你知道有一天会在 PHP 的未来版本之一中实现吗?

【问题讨论】:

    标签: php types oop


    【解决方案1】:

    您可以在当前类中拥有其他类对象,但您必须在使用前将其放在 __contractor(或其他地方)中。

    class Foo {
      private Bar $f1;
      public Bar2 $f2;
      public function __construct() {
        $f1 = new Bar();
        $f2 = new Bar2();
    }}
    
    class Bar1 {...}
    class Bar2 {...}
    

    【讨论】:

      【解决方案2】:

      除了已经提到的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
      

      @var annotation 将帮助一些 IDE 提供代码协助。

      【讨论】:

      • 不错的替代品,非常适合文档用途。
      【解决方案3】:

      您可以指定对象类型,同时通过 setter 方法的参数中的类型提示将对象注入 var。像这样:

      class foo
      {
          public bar $megacol;
          public bar2 $megasupercol;
      
          function setMegacol(bar $megacol) // Here you make sure, that this must be an object of type "bar"
          {
              $this->megacol = $megacol;
          }
      
          function setMegacol(bar2 $megasupercol) // Here you make sure, that this must be an object of type "bar2"
          {
              $this->megasupercol = $megasupercol;
          }
      }
      

      【讨论】:

      • 我不知道以这种方式重载方法是可能的。不错。
      【解决方案4】:

      您正在寻找的称为类型提示,自 PHP 5 / 5.1 起在函数声明中部分可用,但不是您希望在类定义中使用它的方式。

      这行得通:

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

      但这不是:

      class MyClass
        {
          public OtherClass $otherclass;
      

      我不认为这是为未来计划的,至少我不知道它是为 PHP 6 计划的。

      但是,您可以在对象中使用 getter and setter functions 来强制执行您自己的类型检查规则。不过,它不会像OtherClass $otherclass 那样优雅。

      PHP Manual on Type Hinting

      【讨论】:

      • 需要注意的是,TypeHinting 对标量类型不可用(目前)。
      • @Gordon:没错。但当然,您可以在方法内的简短 if 条件中检查特定类型。如果不满足,则通过给定的参数抛出异常。
      • @faileN 是的,类似于is_scalar() 或任何特定的 is_* 函数。
      【解决方案5】:

      没有。函数参数可以使用type hinting,但不能声明变量类型或类属性。

      【讨论】:

        猜你喜欢
        • 2021-12-09
        • 1970-01-01
        • 2017-06-29
        • 1970-01-01
        • 2017-02-25
        • 2017-09-08
        • 1970-01-01
        • 2020-12-25
        • 2015-01-18
        相关资源
        最近更新 更多