When we use public static in oops concepet in php

Hi

when we use public static and public function why we use it ,any one give me suggestion

Static methods come in handy when we don’t need to rely on the class instance for the data but either the default properties and constants or parameters we choose to pass to the function, the main two differences are the way you call the function which is by the CLASS name then two :: colons followed by the name of the function which would end up looking like:

myClass::someFunction()

The second difference is instead of using $this which refers to the instance of the class you use self:: which refers to the class statically allowing you to access default property values and constants, that would look something like the following:

class myClass {
    $someProperty = 'something';
    
    public static function someFunction() {
        echo self::$someProperty; // Will always return "something"
    }
}

Pretty much the only time I ever use them is if I’m dealing with a class that needs multiple instances but only uses some methods to run data comparisons and things like that, anything specific to the class instance I will make it a normal public function.

Thanks for you answer, this help me a lot to understand about the use of public static.

Static it’s often used in singleton, for database connections.
The main property (short story) of a static is that it remains defined so, a database connection (as example) will not be defined twice.
I did a simple example for you, for a better understanding.
Check the “— init” in both cases.

<?php

class db {

	public static $stat = null;
	public $nonstat = null;
	
	public function __construct( $con ) {
		if(!self::$stat) {
			self::$stat = 'static '.$con;
			echo "\
--- init STATIC!";
		}
		if(!$this->nonstat) {
			$this->nonstat = 'non-static '.$con;
			echo "\
--- init non-STATIC!";
		}
	}

}

echo '<pre>';
$db = new db(1);
echo "\
Have static: " . db::$stat;
echo "\
Have non-static: " . $db->nonstat;
echo "\
========================";
$db1 = new db(2);
echo "\
Have static: " . db::$stat;
echo "\
Have non-static: " . $db1->nonstat;

?>

this will return

--- init STATIC!
--- init non-STATIC!
Have static: static 1
Have non-static: non-static 1
========================
--- init non-STATIC!
Have static: static 1
Have non-static: non-static 2 

There are a few threads here that may be well worth your read
PHP MASTER: singleton, trait and registry examples throw fatal error
Separation of database access between objects and their subordinates

My first link above has a nice discussions on singleton usage (again, very good read, and I’d still argue it isn’t wrong to use a singleton pattern, but just make sure it is something you actually need).