What does private static do in php?

Associate
Joined
4 Mar 2007
Posts
315
Location
United Kingdom
Ok so I set myself up a class such as:

PHP:
class myClass{

 private static $_inst;

 private function __construct(){
  // Execute my constructors here?
   $this->_something();
 }

 private static function getInstance(){
   if(!self::$_inst){
     self::$_inst = new myClass();
   }
   return self::$_inst;
 }

 private function _something(){
   $xyz = "goodbye";
 }

 public function somethingElse(){
   $abc = "hello";
 }

}

I understand that looking at the __construct is the first thing that gets executed correct? So I would go about setting up my constructors here, then calling it in the main file to create an instance.

However why would I need to use private static, and not just private if private is just keeping the data to the particular class? What differs with statics?

In the main file for instance, I could do:

PHP:
require_once('class.myClass.php');
$instance = myClass::getInstance();
$instance->somethingElse();

As somethingElse is a public function so aside yet if I were to do the same with something() it wouldn't work as it is private and relative to the class. So why make a private static?
 
If it wasn't static it wouldn't work. The class above (kind of) uses a singleton pattern, so it tries to ensure you only have one instance of the class.

Static makes sure there is only one copy of the $_inst variable (even if you were to have more than one instance of the class). So if $_inst wasn't static, the static function getInstance wouldn't be able to access the $_inst variable because static functions can't access non-static member variables.
 
Last edited:
Very useful for something like a database connection class where you only want to instantiate one true connection.

It would make the connection the first time a call was made to run a query and thereafter use the same connection for all future queries.
 
Back
Top Bottom