沃梦达 / 编程问答 / php问题 / 正文

何时在 PHP 中使用静态修饰符

When to use static modifier in PHP(何时在 PHP 中使用静态修饰符)

本文介绍了何时在 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 中使用静态修饰符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:何时在 PHP 中使用静态修饰符

基础教程推荐