When should I use Static functions/classes/fields in PHP? What are some practical uses of it?
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.
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.
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.
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.
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With