何时使用静态类与实例化类 [英] When to use static vs instantiated classes

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

问题描述

PHP 是我的第一门编程语言.我不太清楚什么时候使用静态类和实例化对象.

PHP is my first programming language. I can't quite wrap my head around when to use static classes vs instantiated objects.

我意识到您可以复制和克隆对象.然而,在我使用 php 的所有时间里,任何对象或函数总是以单个返回值(数组、字符串、整数)或 void 结束.

I realize that you can duplicate and clone objects. However in all of my time using php any object or function always ended up as a single return (array, string, int) value or void.

我理解书中的概念,例如电子游戏角色类.复制汽车对象并使新的汽车对象变为红色,这一切都说得通,但它在 php 和 Web 应用程序中的应用却不是.

I understand concepts in books like a video game character class. duplicate car object and make the new one red, that all makes sense, but what doesn't is its application in php and web apps.

一个简单的例子.一个博客.博客的哪些对象最好实现为静态或实例化对象?数据库类?为什么不在全局范围内实例化 db 对象?为什么不让每个对象都静态呢?性能怎么样?

A simple example. A blog. What objects of a blog would be best implemented as static or instantiated objects? The DB class? Why not just instantiate the db object in the global scope? Why not make every object static instead? What about performance?

这只是风格吗?有没有合适的方法来做这些事情?

Is it all just style? Is there a proper way to do this stuff?

推荐答案

这是一个很有趣的问题——答案可能也很有趣^^

This is quite an interesting question -- and answers might get interesting too ^^

考虑事情的最简单方法可能是:

The simplest way to consider things might be :

  • 使用实例化类,其中每个对象都有自己的数据(就像用户有名字一样)
  • 当静态类只是一个可以处理其他东西的工具时使用它(例如,将 BB 代码转换为 HTML 的语法转换器;它本身没有生命)

(是的,我承认,真的过于简单化了......)

关于静态方法/类的一件事是它们不利于单元测试(至少在 PHP 中,但可能在其他语言中也是如此).

One thing about static methods/classes is that they don't facilitate unit testing (at least in PHP, but probably in other languages too).

关于静态数据的另一件事是你的程序中只存在它的一个实例:如果你将 MyClass::$myData 设置为某处的某个值,它就会有这个值,而且只有它,无处不在 -- 说到用户,您将只能拥有一个用户 -- 这不是很好,是吗?

Another thing about static data is that only one instance of it exists in your program : if you set MyClass::$myData to some value somewhere, it'll have this value, and only it, every where -- Speaking about the user, you would be able to have only one user -- which is not that great, is it ?

对于博客系统,我能说什么?实际上,我认为我不会写太多静态内容;也许是数据库访问类,但最终可能不是 ^^

For a blog system, what could I say ? There's not much I would write as static, actually, I think ; maybe the DB-access class, but probably not, in the end ^^

这篇关于何时使用静态类与实例化类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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