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?
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.
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 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.
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(::).
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).
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'
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