简体   繁体   English

PHP SPL-是否存在任何接口或类来控制在转换为数组时会发生什么?

[英]PHP SPL - is there any interface or class to control what happens when casting to array?

So by implementing Iterator , ArrayAccess , and Countable built-in interfaces, we have control over what happens inside an object when it's used in foreach loops or if a property is accessed as if it were an array index ( $object['id'] ). 因此,通过实现IteratorArrayAccessCountable内置接口,我们可以控制对象在foreach循环中使用时或在访问属性时就像在数组索引中一样( $object['id'] )。

For example, if you wanted, you could set it up so $object['version'] += 1 could automatically increment version field in the database. 例如,如果需要,可以进行设置,以便$object['version'] += 1可以自动增加数据库中的version字段。

What's missing is casting the object to array . 缺少的是将objectarray Is there any interface or class that allows control over what happens when you do: (array) $object ? 是否有任何接口或类可以控制执行以下操作时所发生的情况: (array) $object Any built-in interface or class at all, no matter how obscure? 任何内置接口或类,无论多么晦涩? For example: if I wanted (array) $object to return $this->propertyArray instead of the normal object to array conversion of dumping all public object properties? 例如:如果我想(array) $object返回$this->propertyArray而不是普通对象到转储所有公共对象属性的数组转换?

Note: something like requiring calling $object->toArray() by method name doesn't count, as the idea is to minimize the outside differences between an array and object as much as possible. 注意:诸如要求通过方法名称调用$object->toArray()类的东西不计在内,因为其想法是尽可能减少数组与对象之间的外部差异。

no there is not , because toArray() is not an magic function like __toString(); 不,没有,因为toArray()并不是像__toString()这样的魔术函数; where casting works eg 铸造工作的地方,例如

$foo = (string) $myObect;

you have to specify toArray() and inside it return your array , may be in future __toArray() might come. 您必须指定toArray()并在其中返回您的array,可能在将来__toArray()可能出现。

You could add a method like this 您可以添加这样的方法

public function toArray() {
    return get_object_vars( $this );
}

See here . 看这里 Or check SplFixedArray::toArray . 或检查SplFixedArray :: toArray

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM