【问题标题】:PHP: Count an ArrayAccess object without CountablePHP:计算没有 Countable 的 ArrayAccess 对象
【发布时间】:2018-04-07 23:46:16
【问题描述】:

所以我正在使用一些我没有完整源代码的外部 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 调用SpecialArray->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 ]
      }
    }
  }
}

【问题讨论】:

  • 如果能循环进去,为什么不手动计数??
  • 出于好奇,您如何处理没有源代码的外部 PHP 代码?
  • 正确的计数不会是 1,是吗?
  • 如果是 1 我们知道答案;)
  • @MagnusEriksson 有困难...

标签: php arrayaccess countable


【解决方案1】:

测试你的代码后,我得到的返回值是1。我引用count()的PHP手册:

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

从 PHP 7.2 开始,尝试在不可数的事物上使用 count() 会发出警告,例如

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

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

【讨论】:

  • 感谢您的回答,但count(SpecialArray) 正在返回正确的计数,例如,如果 SpecialArray 中有 7 个元素(我可以在 foreach 中循环等),count(SpecialArray) 返回 7 !!!!
  • 你有更多的代码给我们吗?这样我们就不会走远了。
猜你喜欢
  • 2011-07-14
  • 2015-01-30
  • 2011-02-19
  • 1970-01-01
  • 2012-03-30
  • 2014-03-16
  • 1970-01-01
  • 2013-04-18
  • 2019-11-07
相关资源
最近更新 更多