何时在PHP中使用静态修饰符 [英] When to use static modifier in PHP

查看:71
本文介绍了何时在PHP中使用静态修饰符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我在做一些代码审查时,遇到了许多类,其中包含大量静态方法……而我似乎无法理解为什么?因此,我的问题是:

Doing some code reviews lately I came across a number of classes that have significant number of static methods in them... and I can't seem to grasp why? Hence my question:

有关在PHP中使用静态方法的最佳实践是什么?

What are the best practices regarding using static methods in PHP?

一个人何时要使用它们,什么时候不应该使用它们?

When would one want to use them and when would one shouldn't use them?

运行时如何处理静态方法有哪些具体区别?它们会影响性能或内存占用吗?

What are specific difference in how runtime handles static methods? Do they affect performance or memory footprint?

推荐答案

最近做了一些代码审查,我遇到了许多类,其中包含大量静态方法...而我似乎无法理解为什么

Doing some code reviews lately I came across a number of classes that have significant number of static methods in them... and I can't seem to grasp why

PHP在5.3之前没有命名空间,因此所有函数/变量都属于全局范围,除非它们属于某个类.将它们作为静态成员放在一个类中是解决不使用命名空间的一种方法(这也许就是为什么您看到它们以大量"数字显示)的原因

PHP didn't have namespaces before 5.3, so all function/variables would be in global scope unless they belonged in some class. Putting them in a class as static members is a workaround for not having namespaces (and that's probably why you saw them in "significant" number)

通常,它们用于在单个对象中用处不大的功能,但在类级别上有一些用途(如其他答案所述)

Generally, they are used for functions that aren't much useful in individual objects, but has some use at class level (as said in other answers)

这篇关于何时在PHP中使用静态修饰符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆