How to use static keyword in php with example 2021 |
How to use static keyword in php with example
static keyword in PHP: A static keyword is an important element in PHP which is mainly used for memory management. The static keyword can be used with variables and functions. static members belong to the class rather than the object of the class so they can be called by class name directly.
Java Language
Static Variable: The variable which is declared with static keyword is called a static variable. It is also called class level variable because it is common to all instances(object). A static variable can be accessed anywhere in the program using class name and:: (scope resolution) symbol.
How to use static variables in PHP for example?
<?php class Program { static $y=20; public function test() { static $x=10; echo $x."<br>"; $x++; } } $obj = new Program(); $obj->test(); $obj->test(); echo Program::$y; ?> *****OUTPUT***** 10 11 20 |
static function: The function which is declared with static keyword is called static function or method. A static function is also called by class name directly because it belongs to the class rather than an object. scope resolution(::) symbol is used to call a static method.
Python Language
How to use the static function in PHP for example
<?php class Arithmetic { static public function add() { $x=40; $y=20; echo "Two Value Sum:".($x+$y)."<br>"; } } Arithmetic::add(); ?> *****OUTPUT***** Two Value Sum:60 |
The calling of static function within the class self keyword is used to call a static function within the same class.
PHP Language
How to use the static function within the class in PHP?
<?php class Arithmetic { static public function add() { $x=10; $y=20; echo "Two Value Sum:".($x+$y)."<br>"; } public function sub() { $x=90; $y=20; echo "Two Value Subtraction:".($x-$y)."<br>"; self::add(); } } $obj=new Arithmetic(); $obj->sub(); ?> *****OUTPUT***** Two Value Subtraction:70 Two Value Sum:30 |
0 Comments