Is there any difference between a global function and wrapping such function into a namespaced class?

40 views Asked by At

Suppose you have a global method().

You can move it into a namespace and a class, and call it something like

\\Namespace\Class::method();

Is there any difference? Is one better than another?

Essentially you have not change anything and the method is for all intents and purposes just as global as it has been before - you can still call it from anywhere, but you have to type more characters. Did I miss something embarrassingly basic?

1

There are 1 answers

0
yivi On BEST ANSWER

Namespaces and classes will not only help you with compartimentalization of your code and help you avoid name collissions, but actually make it faster by being able to use autoloaders and only load what you need when you need it.

It's very unlikely you'd call your method like this:

\\Namespace\Class::method();

You are much more likely to declare use Namespace\Class statements at the top of your file, and just do Class::method();.

And even more likely (and quite probably better) you'll actually instantiate a real object instead of using static methods (which are convenient, but can really break down encapsulation). In your example you are using an static method, which for a lot of people are not particularly object-orientedy.

Functionally, considered in isolation, there is no real difference between a method and a function. But a method has access to class properties and private methods, so it further helps you to build a system where responsibilities are properly distributed.

But to be meaningful, the difference has to be more than cosmetic. If you are using classes and objects, read on SOLID principles and design patterns (a bit at a time) and embrace the advantages of OOP.