PHP 中的静态方法:有什么用? [英] Static methods in PHP: what for?

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

问题描述

我很抱歉问这样一个愚蠢的问题,但我是 OOP 的新手并试图弄清楚静态方法的用途.这是一个示例 PHP 代码:

I'm terribly sorry for asking such a silly question, but I'm new to OOP and trying to figure out what static methods are used for. Here's an example PHP code:

class foo{
static function bar(){
//do something here
}
public function baz(){
//do something different
}
}

文档 说:

将类属性或方法声明为静态使它们无需实例化即可访问

Declaring class properties or methods as static makes them accessible without needing an instantiation of the class

然而,上面例子中的两个方法都可以从类的外部访问:

However, the both methods from the example above can be accessed from outside of the class with like:

foo::bar();
foo::baz();

它无需实例化类 foo 即可工作(至少对于我正在使用的 PHP 5.3).那么,如果两种方式都有效,那么使用静态方法的意义何在?

It works (at least for PHP 5.3 that I'm using) without instantiation of the class foo. So, what's the point of using static methods, if the both ways work??

再次原谅我提出这样一个菜鸟问题.我一直在努力寻找自己,但没有成功.谢谢.

Forgive me once again for such a noob question. I've been really trying hard to find it out myself with no success. Thanks.

推荐答案

静态方法是全局可用的工具(帮助程序)并且经常被过度使用.静态方法会破坏可测试性,应该几乎完全避免.

Static methods are globally available tools (helpers) and are often overused. Static methods are death to testability and should be avoided almost completely.

它们的优点和缺点是它们存在于全局范围内,您可以从任何地方调用它们,这使得它们在大多数情况下代码异味,因为它们破坏了封装.

Their advantage as well as disadvantage is that they live in the global scope, you can call them from anywhere, which makes them code smells in most cases because they break encapsulation.

在语言层面,正如 Kolink 所提到的,mysqli:real_escape_string() 之类的东西当然是有意义的,但在应用层面,你通常不想污染你的全局范围并破坏封装,比如那.您更愿意考虑您真正需要哪些工具以及在哪里将它们捆绑到有意义的组(类)中.

On language level, as Kolink mentions, things like mysqli:real_escape_string() make sense of course, but on application level, you usually don't want to pollute your global scope and break encapsulation like that. You'd rather think of what tools you really need and where and inject them bundled into meaningful groups (classes).

您的 foo::baz() 在严格模式下(应该始终打开)引发警告:

Your foo::baz() raises a warning in strict mode (which should always be on):

严格的标准:非静态方法 foo:baz() 应该不在 yourfile.php 中静态调用 x 行

Strict standards: Non-static method foo:baz() should not be called statically in yourfile.php on line x

这篇关于PHP 中的静态方法:有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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