0

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?

Dennis
  • 7,907
  • 11
  • 65
  • 115
  • It is better if you think you might have two function called `method()` and you will need both of them. Namespaces are useful to seperate diffrent function with the same name. – Nicolas Jan 04 '17 at 16:08
  • 1
    Namespaces prevent collisions, and let you index your functions to a defined scope, so it's easier to manage a large number of functions. The namespace should tell you roughly what type of functionality they accomplish better than a single method name alone could do. – mopsyd Jan 04 '17 at 16:10
  • As I understand so far, the difference is *compartmentalization*. Which as a bonus allows for same-named methods to exist in different compartments. – Dennis Jan 04 '17 at 16:12

1 Answers1

1

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.

yivi
  • 42,438
  • 18
  • 116
  • 138