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

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

问题描述

PHP是我的第一个编程语言。当我使用静态类和实例化对象时,我不能完全包装。



我意识到你可以复制和克隆对象。但是在我所有的时间使用php任何对象或函数总是作为单个返回(数组,字符串,int)值或void。



像一个视频游戏角色类。 重复的汽车对象,并使新的一个红色,这一切都有意义,但不是它的应用程序在PHP和网络应用程序。



一个简单的例子。博客。博客的什么对象最好实现为静态或实例化对象? DB类?为什么不在全局范围内实例化db对象?为什么不让每个对象静态?那么性能怎么样?



这只是风格吗?

解决方案

这是一个有趣的问题,答案可能会很有趣哦^ ^



最简单的考虑方式可能是:




  • 类,其中每个对象都有自己的数据(如用户有一个名称)

  • 使用静态类,当它只是一个工具在其他东西(例如,转换器的BB代码到HTML;它没有自己的生活)



真的真的过度简化...)



静态方法/类的一个事情是,它们不便于单元测试(至少在PHP,但也可能在其他语言)。



另一件关于静态数据的事情是,它的程序中只存在一个实例:如果你将MyClass :: $ myData设置为some价值在某个地方,它会有这个值,只有它,每一个地方 - 说到用户,你只能有一个用户 - 这不是那么好,是吗?



对于博客系统,我能说什么?没有多少我写作静态,实际上,我想;也许DB访问类,但可能不是,到最后^^


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

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.

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.

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 :

  • use an instanciated class where each object has data on its own (like a user has a name)
  • use a static class when it's just a tool that works on other stuff (like, for instance, a syntax converter for BB code to HTML ; it doesn't have a life on its own)

(Yeah, I admit, really really overly-simplified...)

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

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天全站免登陆