PHP“重载”方法签名的歧义消除
我有一个通过利用 func_get_args 来确定方法签名来支持复杂“重载”的方法。然而,在某些情况下,参数类型太模糊而无法区分。
designGarment('my shirt', SIZES::XXL, FABRICS::COTTON);
designGarment('my dress', FABRICS::SILK, ATTIRES::PARTY);
在上面的示例中,两个方法签名都解析为 STRING、INT、INT,因为 SIZES、FABRICS 和 ATTIRES 是为其各自属性定义了整数常量的类。我希望能够区分 (STRING, SIZES, FABRICS) 签名和 (STRING, FABRICS, ATTIRES) 签名。这在 PHP 中可能吗?
I have a method that supports complex "overloading" by utilizing func_get_args to determine the method signature. In some situations however, the argument types are too ambiguous to make a distinction.
designGarment('my shirt', SIZES::XXL, FABRICS::COTTON);
designGarment('my dress', FABRICS::SILK, ATTIRES::PARTY);
In the example above, both method signatures resolve to STRING, INT, INT because SIZES, FABRICS and ATTIRES are classes with integer constants defined for their respective properties. I want to be able to distinguish a (STRING, SIZES, FABRICS) signature from a (STRING, FABRICS, ATTIRES) signature. Is this possible in PHP?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用对象而不是猜测参数:
或者使用键/值对数组来显式指定参数及其值:
Use objects instead of guessing arguments:
Or use an array of key/value pairs to explicitly specify arguments and their values:
除了@Brad Christie 的答案之外,还有其他一些:
推荐:按常量顺序使用参数,并使用 null 作为缺失参数的默认值
使用对象存储可选参数
为每种类型的属性创建单独的对象
与上面类似,但为每种类型和属性值创建单独的对象(不推荐,但我见过一些使用此方法的情况)< /p>
Beside @Brad Christie answer there are few others:
Recomended: use arguments in constant order and null as default values for missing ones
Use Object to store optional arguments
Make separeate object for every type of property
Similar to above, but to have separate object for every type and value of property (not recommended, but I've seen some cases using this)