On 17/11/2019 23:01, Mike Schinkel wrote:

    Consider this: __toArray() is hardly a rare case where a short
    name can be applied in multiple contexts.  We have infinite
    contexts where we need to name methods for one context that might
    conflict with others, and so I have been agonizing for years over
    how to deal with this conundrum without resorting to really long
    method names.


I'm not sure avoiding the name "toArray" necessarily leads to "really long method names" - even with extremely specific distinctions, you don't need to call the method "toJsonArrayForVersion5OfTheApi", just "toV5Json" or "getV5Array" or "formatForJsonV5".

The important thing is that the method name is now communicating its *purpose*, whereas "toArray" communicates only its return type, and a hugely flexible return type at that.



    Recently I have been experimenting with using namespaces instead
    of long method names, and I think using them can result in the
    best of both worlds and resolve your concern.  Consider the
    following classes, each of which could have their own __toArray()
    method /specific/ to their use-case:

        
\Widgets\Widget\Widgets\JSON\Widget\Widgets\Mustache\Widget\Widgets\DbColumns\Widget


I'm not clear what these objects represent. If I have a Widget object passed out from some business logic, how do I make use of these other classes? Would I have to call "(array)(new \Widgets\Mustache\Widget($myWidget))", as sugar for "(new \Widgets\Mustache\Widget($myWidget))->__toArray()"?

If so, I don't really see the benefit of the magic method over just standardising a method name, like "interface MustacheFormatter { public function getData(): array; }"

Which is basically my objection to __toArray() - I can't think of many situations where writing (array)$foo saves or gains you anything over writing $foo->asArray() or $foo->somethingMoreSpecific()


Regards,

--
Rowan Tommins (né Collins)
[IMSoP]

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to