I am looking for a better understanding of how static methods work in php. I have been reading the article on the php manual site about static keyword in releation to methods, and class objects and I am curious about something.
Lets say I have this class:
class Something{
protected static $_something = null;
public function __construct($options = null){
if(self::$_something === null && $options != null){
self::$_something = $options
}
}
public function get_something(){ return self::$_something }
}
So you instantiate this on index.php
, so you do something like:
$class_instantiation = new Something(array('test' => 'example'));
Great, at this point $_something
contains an array of key=>value
, on this same page we can do:
var_dump($class_instantiation->get_something()); // var dumps the array we passed in.
BUT
If we now create sample.php
and do:
$class_instantiation = new Something();
var_dump($class_instantiation->get_something());
We get null
back (I assume you went to index.php
, instantiated the class and passed in the array, saw the var_dump
THEN navigated to sample.php
. It is understandable how this would return null
if you only went to sample.php
without first going to index.php
.)
I assumed that static methods are "saved across all instances of the class", thus I should be able to instantiate the class with or with out an object passed into the constructor, assume that something is there and get back my array we created on index.php
So my question is:
How does static methods really work in terms of classes? Is there a way to do what I am trying to do with out the use of third party tools if I am just passing objects around?