我想知道属于集合类的对象是否在迭代时可以知道它正在被迭代并知道它所属的集合类?例如
<?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校长,但我想我还是要问!