When to use static methods/fields in PHP?
W开发者_StackOverflowhen should I use Static functions/classes/fields in PHP? What are some practical uses of it?
you should not, it's rarely useful. common usage for statics are factory methods and singleton::instance()
factory:
class Point{
private $x;
private $y;
public function __construct($x, $y){
...
}
static function fromArray($arr){
return new Point($arr["x"], $arr["y"]);
}
}
singleton:
class DB{
private $inst;
private function __construct(){
...
}
static function instance(){
if ($this->inst)
return $this->inst;
return $this->inst = new DB();
}
}
Usage of static methods in same in languages like Java/PHP.
One simple example can be that you want to use a variable across all instances of your class and any instance can change its value and you want it to get reflected in other instance as well.
class Foo{
static $count=0;
public function incrementCount(){
self::$count++;
}
public function getCount(){
return self:$count;
}
}
Without static you can't set count value via one object and access it in others.
I occasionally use STATIC Methods when I need simple functions in a Class that I also use outside the Class such as:
in a UserProfile class I have an method that returns an array that is used to pass data back to the class after the array is populated from the html page.
Class UserProfile{
Public Static get_empty_array(){
return array('firstname'=>'',lastname=>''); //usually much more complex multi-dim arrays
}
}
This way the empty array can be used within the class/object and outside as a starting template. I also use Static Methods for functions that would normally be standalone functions but I want to keep them in the class so it is all together but also make them available outside as a static method such as:
public static convert_data($string){
//do some data conversion or manipulating here then
return $ret_value;
}
$converted_data = class::convert_data($string);
I do maintain an library of common user defined functions but I have found it handy to include some in the class to which it is closely related.
精彩评论