What are static and dynamic variables / methods in OOP?

社会主义新天地 提交于 2019-12-02 09:36:41

"Static" and "dynamic" aren't the right descriptions for that.

-> indicates a instance functions or instance data, meaning that the function or data has an implicit $this reference. To put it another way you're referring to the function or variable within a particular object.

:: indicates a class function or class variable. This is very similar to a global function or variable in that there is no implicit $this reference. All instance of that class share that function or variable.

"Dynamic" would be a more accurate description for, say, PHP overloading where you can "dynamically" create variables, for example, using the magic methods __get() and __set() (which are called when you try to access a property that can't be found; you can overload these methods to essentially pretend the requested member exists).

Quoting the static page in the PHP manual :

Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. A property declared as static can not be accessed with an instantiated class object (though a static method can).

Also note that when declaring a property as static, there will be only one version of that property for the whole script : static methods/properties "act at the class level rather than at the instance level" (quoting wikipedia).


About advantages / disadvantages, it's a bit hard to answer clearly, as those are just not the same...

The question is : what do you need ?

If you have an object that contains data, and want methods to deal with that data, you'll use dynamic properties and methods.

On the other hand, if you just want to use a class as container for methods that deal with external data (ie, not internal to the class), you'll probably use static methods.
For instance, I am sometimes using static methods as wrappers to libraries that don't export an Oriented-Object API : it allows me to call one class::method, instead of several functions.


Some would say an "advantage" of static methods is that you don't need to instanciate the class to use them -- that is true ; but it also means that you don't get objects, with methods working on them ; well : as I said, using static or not depends on what you need.

Oh, I almost forgot : if you are willing to use unit-testing, you might find out that static methods are not easy to test ; for instance, see Static Methods are Death to Testability.

And static properties (same with singleton and registry design patterns, which rely on static properties/methods) kind of imply "global state", like "global variables" -- which some don't quite like ^^

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!