1

所以我正在使用一些我没有完整源代码的外部 PHP 代码。我正在使用反射来制定可调用的方法等。

他们有这样的课程:

class SpecialArray implments \ArrayAccess
{
    public function offsetExists($index){}
    public function offsetGet($index){}
    public function offsetSet($index, $value){}
    public function offsetUnset($index){}
}

所以逻辑上我可以foreach(SpecialArray),那很好。

但是在代码中,我可以通过某种方式count(SpecialArray)获得正确的计数,例如,如果 SpecialArray 中有 5 个元素,count(SpecialArray)则返回 5!

但是,该类中没有count方法,该类也没有实现Countable CallingSpecialArray->count()也失败了Call to undefined method

有谁知道他们如何做这种巫毒魔法?

满的\ReflectionClass::export()

Class [  class ThirdParty\SpecialArray implements ArrayAccess ] {

  - Constants [0] {
  }

  - Static properties [1] {
    Property [ public static $_metadata ]
  }

  - Static methods [1] {
    Method [  static public method &getMetadata ] {

      - Parameters [0] {
      }
    }
  }

  - Properties [0] {
  }

  - Methods [5] {
    Method [  public method offsetExists ] {

      - Parameters [1] {
        Parameter #0 [  $index ]
      }
    }

    Method [  public method offsetGet ] {

      - Parameters [1] {
        Parameter #0 [  $index ]
      }
    }

    Method [  public method offsetSet ] {

      - Parameters [2] {
        Parameter #0 [  $index ]
        Parameter #1 [  $value ]
      }
    }

    Method [  public method offsetUnset ] {

      - Parameters [1] {
        Parameter #0 [  $index ]
      }
    }

    Method [  public method fetch ] {

      - Parameters [1] {
        Parameter #0 [  $index ]
      }
    }
  }
}
4

1 回答 1

2

测试您的代码后,我得到了返回值 1。让我引用 PHP 手册count()

返回 array_or_countable 中的元素数。当参数既不是数组也不是实现了 Countable 接口的对象时,返回 1。有一个例外,如果 array_or_countable 为 NULL,则返回 0。

从 PHP 7.2 开始,尝试使用count()不可数的东西会给出警告,例如

参数必须是数组或实现了 Countable 的对象

演示https://3v4l.org/G0pR3

于 2017-10-26T14:36:59.553 回答