重载类属性时验证 setter 的 php 最佳实践

发布于 2024-09-26 04:50:08 字数 244 浏览 0 评论 0原文

我有一个使用 __set 魔术方法的类。该类的属性之一只能设置一定范围的字符串值,我能想到的最好的例子是 mysql 数据类型 ENUM('value_one','value_two','value_third')。

我是否可以在 __set 方法中放置条件语句来区分正在设置的属性以及该值对于该属性是否有效?

__set 方法中的大型 switch 语句是否被认为是草率的做法,它们是产生所需结果的更好方法吗?

谢谢, 本

I have a class that uses the __set magic method. One of the properties for the class can only be set with a certain range of string values, the best example I can think of is the mysql datatype ENUM('value_one','value_two','value_three').

Would I place conditional statements within the __set method to distinguish between which property is being set and whether the value is valid for that property?

Are large switch statements inside a __set method considered sloppy practice, is their a better way of producing the desired results?

Thanks,
Ben

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

孤寂小茶 2024-10-03 04:50:08

我可以放置条件语句吗
__set方法内区分
正在设置的属性之间
以及该值是否有效
该属性?

第一部分是,第二部分不是。

大型 switch 语句是否位于
__set方法被认为是草率的做法,是他们更好的方法
产生期望的结果?

您的 __set 方法应确定尝试设置哪个变量,然后将其余功能传递给私有设置器 setPspecialVar。然后,setPspecialVar 将包含特定于验证该变量的逻辑,并且如果传递了无效值,则可能会引发异常。

或者,您可以将私有设置器设为公共,从而允许两种方式设置变量,但这并不理想,因为两种设置值的方式不是干净的设计。

Would I place conditional statements
within the __set method to distinguish
between which property is being set
and whether the value is valid for
that property?

Yes to the first part, no to the second.

Are large switch statements inside a
__set method considered sloppy practice, is their a better way of
producing the desired results?

Your __set method should determine which variable is trying to be set and then pass off the rest of the functionality to a private setter setParticularVar. setParticularVar will then contain the logic specific to validating that variable and can throw an exception if an invalid value is passed.

Alternatively, you could make the private setter public instead, allowing two ways to set the variable but this is not as desirable as two ways to set a value is not as clean a design.

隔纱相望 2024-10-03 04:50:08

__set 函数可以检查是否存在名为类似于 presetVariableName 的方法,该方法被调用并将新值作为参数传递。

然后,该函数可以执行验证逻辑,并返回 truefalse 以确定其是否有效。

The __set function could check for the existance of a method named similar to presetVariableName, which is called and passed the new value as a parameter.

That function could then perform the validation logic, and return true or false as to whether it's valid or not.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文