小编Sla*_*uip的帖子

当作为集合的一部分迭代它们时,是否可以拦截对象的方法?

我想知道属于集合类的对象是否在迭代时可以知道它正在被迭代并知道它所属的集合类?例如

<?php
class ExampleObject
{
    public function myMethod()
    {
        if( functionForIterationCheck() ) {
           throw new Exception('Please do not call myMethod during iteration in ' . functionToGetIteratorClass());
        }
    }
}

$collection = new CollectionClass([
    new ExampleObject,
    new ExampleObject,
    new ExampleObject
]);

foreach($collection as $item) {
    $item->myMethod(); //Exception should be thrown.
}

(new ExampleObject)->myMethod(); //No Exception thrown.
Run Code Online (Sandbox Code Playgroud)

我做了一些谷歌,但找不到任何东西,我猜这是不可能的,因为它打破了某个地方的OOP校长,但我想我还是要问!

php oop iterator proxy-object

6
推荐指数
1
解决办法
112
查看次数

标签 统计

iterator ×1

oop ×1

php ×1

proxy-object ×1