Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use static methods/fields in PHP?

Tags:

php

static

When should I use Static functions/classes/fields in PHP? What are some practical uses of it?

like image 290
Ali Avatar asked Apr 02 '11 07:04

Ali


People also ask

When should I use static methods in PHP?

The static keyword is used to declare properties and methods of a class as static. Static properties and methods can be used without creating an instance of the class. The static keyword is also used to declare variables in a function which keep their value after the function has ended.

When should static methods be used?

You should consider making a method static in Java : 1) If a method doesn't modify the state of the object, or not using any instance variables. 2) You want to call the method without creating an instance of that class.

Why do you need static fields or methods?

A static method has two main purposes: For utility or helper methods that don't require any object state. Since there is no need to access instance variables, having static methods eliminates the need for the caller to instantiate the object just to call the method.

Where should you use a static method?

Static methods are usually preferred when: All instance methods should share a specific piece of code (although you could still have an instance method for that). You want to call method without having to create an instance of that class. You must make sure that the utility class is never changed.


1 Answers

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();
  }
}
like image 123
Kamil Tomšík Avatar answered Sep 22 '22 13:09

Kamil Tomšík