#2: When you are using a class only for context.
Sometimes, you want to define a function inside a class just to give it the right context.
For example, let’s say that you have a User class, and a idFromName($name) method that returns a user’s ID from its name.
If this method does not use any class properties or methods, then there are no technical reasons for it to be inside the User class.
However, you may want to keep it inside the class to give it a specific context: this way, you know that this function is about users.
By doing this, you can also avoid adding a “user” prefix in the function’s name.
This seems like a valid reason to keep this function inside the class.
But if context is the only reason, you can achieve the same result by using Namespaces.
Instead of defining the function as a User class method, you can define it inside a Namespace like this:
Namespace Users;
function idFromName($name)
{
/* do your stuff… */
}
This gives the function its context, and you can keep using a short name because the namespace’s syntax makes it clear it’s about users:
$id = Users\idFromName($name);
|