魔术方法是 PHP 中的最佳实践吗?
魔术方法是 PHP 中的最佳实践吗?
Are Magic Methods Best practice in PHP?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
魔术方法是 PHP 中的最佳实践吗?
Are Magic Methods Best practice in PHP?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(4)
缺点
文本搜索找不到功能
系统更难理解,尤其是对于新手来说
重构工具可能会更频繁地失败
通常,魔术方法在幕后做事,程序员可能没有意识到它正在发生,这使得调试变得更加困难。
当搜索函数(或其他符号)无法找到所有匹配项时,删除旧代码将成为一场噩梦,并且这种恐惧可能会导致死代码堆积在代码库中。如果删除死代码,可能会导致未知位置的损坏。
cons
Text searches don't find the functions
System is harder to understand, especially for newcomers
Refactoring tools might fail more often
Generally, the magic methods do things behind the scenes and the programmer might not realize it's happening which makes debugging harder.
When searching for the functions (or other symbols) can't find all the matches it becomes a nightmare to remove old code and this fear can cause dead code to pile up in the codebase. If the dead code is removed, it can cause breakage in unknown places.
我不认为魔法方法是最好或最差的做法:取决于你想要实现的目标,你可以使用或不使用它们......
我的意思是,您不必尽可能调整代码来使用它们,但如果必须的话,根本没有问题。
如果你有一个具有 3 个且只有 3 个属性的对象,则不需要使用魔法 setter/getter,但在某些高级情况下,它们是完成非常复杂的事情(ORM 系统等...)的好方法。
也许其中一些是否已被弃用,我不知道,但大多数都没有。
I don't think magic methods are best or worst practice: depending on what you want to achieve you can use them or not...
What I mean is that you don't have to tweak your code as possible to use them, but if you have to there is no problem at all.
If you have an object with 3 and only 3 attributes you don't need to use magic setters/getters, but in some advanced cases they are a great way to do very complex things (ORM systems etc...)
Maybe some of them are deprecated, I don't know, but most of them are not.
至少,其中一些神奇的功能是谷歌推荐的:
原始链接:http://code.google.com/speed/articles/optimizing -php.html
存档版本:https://web.archive.org/web/20120208060457/http://code.google.com/speed/articles/optimizing-php.html
无论如何,这些方法可能不会表现出色,但它们根本没有被弃用。
At least, some of these magic functions are recommended by Google:
Original link: http://code.google.com/speed/articles/optimizing-php.html
Archived version: https://web.archive.org/web/20120208060457/http://code.google.com/speed/articles/optimizing-php.html
Anyway, these methods might not be performant, but they ain't deprecated at all.
我不这么认为。我的 IDE 无法向我显示魔术 setter 和 getter 的“提示”。尽管代码有时更难调试。
我宁愿不使用它们,更好地通过我的IDE生成所需的方法(如许多设置器和获取器)。
I don't think so. My IDE is not able to show me "hints" for magic setter and getters. Altough the code is harder to debug sometimes.
I prefer not using them, better generate needed methods (like many setters and getters) by my ide.