1

First I know the basics of PHP, but I just can't understand how things work. I have the following code which will allow users to assign password to their accounts through the function hooksInit() by initiating the function init(). I need to know why using the static variable. I've read that without this static variable there will be a lot of request from database, but I couldn't understand why will be a lot of request from database. Please keep it simple if possible.

class WPHawy_CRP {

private static $_instance = null;


/*
* The Constructor.
*/
public static function init() {

    if ( null == self::$_instance ) {

        self::$_instance = new self;

        self::$_instance->hooksInit();

    }

    return self::$_instance;
}
Hemi81
  • 578
  • 2
  • 15
  • 34
Mohamed Omar
  • 453
  • 5
  • 16
  • It's basically ensuring that you're only using one instance of the class, aka. singleton. – rdiz Oct 15 '15 at 12:49

2 Answers2

1

The keyword "static" means that it's a function that you will be able to use without instantiating the class.

For example: WPHawy_CRP::init()

The variable $_instance is also static for the purpose of being used inside static functions.

Specifically, this code follows a specific design pattern called "Singleton", and allows you to ensure you will have only 1 instance of a class.

Max Hanglin
  • 186
  • 1
  • 5
  • this is exactly what happened but what makes me preserve the static variable's value . i just think that this is a modification for the login page of wordpress that allows user to add their own password . and i think this class would be called once for one user so what makes this to apply more requests to the database which why the class uses static variable. sorry for my bad english – Mohamed Omar Oct 15 '15 at 20:49
0

This is a simple implementation of a singleton pattern. See for example this question. The main advantage of this pattern that is allows only one instance of an object to be used across the web application. This pattern is widely used during database connection where we want to share only one database connection throughout the web application.

Community
  • 1
  • 1
Lukáš Bednařík
  • 2,578
  • 2
  • 15
  • 30
  • Ok. could you please make an example with users registration process. i mean which instance would be used once . any example you want .your not limited to the code i posted. i just need to no how the process goes. – Mohamed Omar Oct 15 '15 at 13:30
  • Maybe this could be good example: http://bornageek.com/101/the-registry-pattern-and-php – Lukáš Bednařík Oct 15 '15 at 15:31
  • thanks man you did you've done your best . i think this post has my answer – Mohamed Omar Oct 15 '15 at 16:01