When to use static methods / fields in PHP?

When should you use static functions / classes / fields in PHP? What are the practical applications?

+5
source share
3 answers

you should not, it is rarely useful. common to statics are factory and singleton :: instance () methods

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();
  }
}
+5
source

Using static methods in languages ​​like Java / PHP.

One simple example might be that you want to use a variable in all instances of your class, and any instance can change its value, and you want it to be reflected in another instance as well.

   class Foo{
    static $count=0;
    public function incrementCount(){
    self::$count++;
    }

   public function getCount(){
    return self:$count;
   }
  }

.

+3

STATIC Methods, , , :

UserProfile , , html-.

    Class UserProfile{

        Public Static get_empty_array(){

            return array('firstname'=>'',lastname=>''); //usually much more complex multi-dim arrays

        }

    }

, / . Static Methods , , , , , :

    public static convert_data($string){

        //do some data conversion or manipulating here then

        return $ret_value;


    }

    $converted_data = class::convert_data($string);

, , .

+1

All Articles