Welcome Guest, Not a member yet? Register   Sign In
Static vs Instanced OOP?
#1

[eluser]Loic Sharma[/eluser]
Hello, I'm a pretty new PHP 'developer', and I have a quick question about static and 'instanced' (that is, $foo->bar(); - I'm not sure how it is truly called) OOP. Quite simply, I sincerely do not get why 'instanced' OOP is used over static OOP so much.

To me, it seems as if static OOP provides much much more flexibility and ease than 'instanced' php. For example (unless you're using CI, of course Tongue ), to get access to a class within another class, you always have to do:

Code:
global $foo;
$foo->bar();

Whereas static allows you to just do:

Code:
foo::bar();

Is the reason why 'instanced' OOP is used over static because it is faster, or stabler? Or is there another reason?

Thanks for reading this, and thank you if you reply. It'll greatly help me learn Smile
#2

[eluser]Jelmer[/eluser]
You can create classes that are static-only. But they're singleton and you can't have multiple instances of them.

There's advantages to both and some implementations might benefit from a static implementation, some can't be implemented as singletons. And some will need a mix of both functionalities.

Think what you need and if static is good for that. Just don't use a single instance with global, that's almost always a bad idea (from a best-practice point of view, not that it doesn't work). Pass objects from one method to another, use parent classes and static classes for global access.

Also CI uses instances instead of static classes because it's still PHP4 compatible and PHP4 didn't have static classes.
#3

[eluser]Loic Sharma[/eluser]
[quote author="Jelmer" date="1281503992"]PHP4 didn’t have static classes[/quote]

Ahh, that'd probably be why then. Thanks Smile
#4

[eluser]jsfmills[/eluser]
The term OOP refers to objects within a system and their interaction with each other.The choice of static vs instance methods is typically more about design.Static fields are useful when you want to store state related to all instances of a class.A counter is a good example of a static field.A static method that creates an instance is an example of a class factory.




Theme © iAndrew 2016 - Forum software by © MyBB