Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php static function

I have a question regarding static function in php.

let's assume that I have a class

class test {     public function sayHi() {         echo 'hi';     } } 

if I do test::sayHi(); it works without a problem.

class test {     public static function sayHi() {         echo 'hi';     } } 

test::sayHi(); works as well.

What are the differences between first class and second class?

What is special about a static function?

like image 738
Moon Avatar asked May 24 '09 02:05

Moon


People also ask

What is a static function in PHP?

Definition and Usage. 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.

Should I use static function PHP?

You should not use static method (in OOP). If you need a static method in one of your class, this means you can create a new singleton/service containing this method and inject it to the instance of classes needing it.

When should I use static methods in PHP?

When to define static methods ? The static keyword is used in the context of variables and methods that are common to all the objects of the class. Therefore, any logic which can be shared among multiple instances of a class should be extracted and put inside the static method.

Does PHP have static variables?

Introduction: A static class in PHP is a type of class which is instantiated only once in a program. It must contain a static member (variable) or a static member function (method) or both. The variables and methods are accessed without the creation of an object, using the scope resolution operator(::).


2 Answers

In the first class, sayHi() is actually an instance method which you are calling as a static method and you get away with it because sayHi() never refers to $this.

Static functions are associated with the class, not an instance of the class. As such, $this is not available from a static context ($this isn't pointing to any object).

like image 147
Jonathan Fingland Avatar answered Oct 08 '22 12:10

Jonathan Fingland


Simply, static functions function independently of the class where they belong.

$this means, this is an object of this class. It does not apply to static functions.

class test {     public function sayHi($hi = "Hi") {         $this->hi = $hi;         return $this->hi;     } } class test1 {     public static function sayHi($hi) {         $hi = "Hi";         return $hi;     } }  //  Test $mytest = new test(); print $mytest->sayHi('hello');  // returns 'hello' print test1::sayHi('hello');    //  returns 'Hi' 
like image 35
user2132859 Avatar answered Oct 08 '22 13:10

user2132859