2

Is it a good idea to create a static member in a class object and call that member for specific function? like:

class Users
{
     public static Login(strUsername, strPassword)
     {
          $objThis = new Users();
          ....
     }
}

and call it like:

Users::Login('admin', 'admin');

or second method:

class Users
{
     public Login(strUsername, strPassword)
     {
          //$objThis = new Users();
          ....
     }
}

and call it like:

$objThis = new Users();
$objThis->Login('admin','admin');
KoolKabin
  • 17,157
  • 35
  • 107
  • 145
  • 1
    If you use the static method, the class can't maintain any state for the user. – alex Apr 19 '11 at 10:15
  • Possibly related: http://stackoverflow.com/questions/752758/is-using-a-lot-of-static-methods-a-bad-thing and http://stackoverflow.com/questions/4685622/what-are-good-reasons-to-use-static-methods-in-php – Maxime Pacary Apr 19 '11 at 10:18

3 Answers3

1

The first method can be useful if you want to restrict access to the class, and not allow it to be instantiated. For example:

class Users {
    private function __construct($strUsername, $strPassword) {
        // this class can now not be instantiated
        // except within itself
    }

     public static Login($strUsername, $strPassword)
     {
          return new self($strUsername, $strPassword);
     }
}

This forces users of your class to always use the static method to get a User object, which can be desirable if you always want to restrict how its used.

As always, it largely depends on what you want to do. static is like a tool, and you use it when it's the right tool for the job on hand.

Craig Sefton
  • 903
  • 11
  • 20
1

These functions are used when

  • You don't want to allow, to create instance of class from outside the class, indirectly you want to make constructor private or protected.
  • Or You want to allow only single instance of class for the whole request(one request). For. eg. Classes for Database, Document etc.
Gaurav
  • 28,447
  • 8
  • 50
  • 80
0

Usually static methods should be avoided - they complicate API and refactoring. I using static methods only as alternative to class constructors when initialization may throw an exception (reading from file, etc) and for private utility methods.

Alex Netkachov
  • 13,172
  • 6
  • 53
  • 85