我什么时候在 php 中使用静态变量/函数? [英] When do I use static variables/functions in php?

查看:31
本文介绍了我什么时候在 php 中使用静态变量/函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 PHP 刷新自己的 OOP,我看到了一个将函数和/或变量设置为静态的示例.何时以及为何将变量/函数设置为静态?我已经完成了其他语言并且不记得曾经使用过静态,我从来没有找到它的真正目的.我知道它的作用,但为什么不直接使用变量呢?

I am refreshing myself on OOP with PHP and I saw an example of setting functions and/or variables as static. When and why would I set a variable/function to static? I've done other languages and don't really recall ever using static, I never found a real purpose to it. I know what it does but why not just use a variable instead?

推荐答案

当您想使用未绑定到实例的方法/变量时,请使用 static.这可能发生在:

You use static when you want to use a method / variable that is not tied to an instance. That can happen when :

  • 与您的目的和实例无关(对于不允许任何其他 OOP 之类的语言(如 Java,但在 PHP 中没有用)的语言中的工具箱很有用).

  • There is no relation with your purpose and an instance (useful for toolboxes in languages that doesn't allow anything else that OOP like Java, but not useful in PHP).

您想控制对实例的访问.大多数情况下,您要处理的实例在您编写代码时并未定义,而是会在执行时定义.单例模式是最好的例子.您可以使用静态方法作为工厂根据上下文创建对象或与其他实例共享资源.E.G:静态成员可以提供对数据库层的访问权限,因此应用程序的一部分可以从任何地方访问相同的应用程序,并且可以在没有冲突的情况下打开/关闭它.

You want to control the access to the instance. Most often, the instance you want to deal with is not defined when you write the code, but will be at execution. The Singleton pattern is the best example. You can use static methods as factories to create an object according to the context or sharing resources with other instances. E.G : a static member can give access to a data base layer so part of the app accesses the same one from anywhere and it's opened/closed without conflicts.

性能很重要,该方法将被执行很多次.在这种情况下,您将节省一些 CPU 时间,防止解释器在每次调用时查找成员到实例.但是,如果 perfs 成为一个问题,以至于您选择此解决方案,那么可能是时候重新考虑您的架构,或者为代码的关键部分使用与更快语言的绑定.

Performances matter and the method will be executed a lot of times. In that case, you will save some CPU time preventing the interpreter from looking up the member to an instance at each call. But still, if perfs becomes such an issues that you come to this solution, it might time to reconsider your architecture, or the use of a binding to a faster language for the critical parts of the code.

您有一个与类型相关但将应用于另一个类型的方法.将方法写入第一种类型的声明是有意义的,但将其设置为静态,因为它需要另一个类型的实例.

You have a method that is related to a type but will be applied to another. It can make sense to write the method into the declaration of the first type, but set it static since it expects an instance of the another one.

完美的例子是字符串解析器:

The perfect example is a String parser :

class MyObject 
{
 static function parse($str)
 {
    $obj = new MyObject();
    // some parsing/setting happens here
    return $obj;
 }
}

// you create an object "MyObject" from a string, so it's more obvious
// to read it this way :
$new_obj = MyObject::parse("This a description of a super cool object");

这篇关于我什么时候在 php 中使用静态变量/函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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