Reputation: 3945
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?
Upvotes: 0
Views: 348
Reputation: 79024
The static property is static
across the same PHP execution. If you run it on index.php
, then at the end of execution it is destroyed. On sample.php
it will be a new execution. This works as you expect (same execution):
//index.php
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; }
}
$class_instantiation = new Something(array('test' => 'example'));
var_dump($class_instantiation->get_something());
$class_instantiation2 = new Something();
var_dump($class_instantiation2->get_something());
Both objects
dump:
array(1) {
["test"]=>
string(7) "example"
}
Upvotes: 1
Reputation: 29932
static
in PHP also means that you could access to property/method without instatiating the class. It's hard to keep static
variables across the same PHP execution as, often, your execution will end with a server response but as AbraCadaver says, they act as you expect within the same execution (same request, read that way)
Upvotes: 1