开发者

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

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)
     {
          /开发者_StackOverflow社区/$objThis = new Users();
          ....
     }
}

and call it like:

$objThis = new Users();
$objThis->Login('admin','admin');


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜