Hi
when we use public static and public function why we use it ,any one give me suggestion
| SitePoint Sponsor |
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:
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:PHP Code:myClass::someFunction()
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.PHP Code:class myClass {
$someProperty = 'something';
public static function someFunction() {
echo self::$someProperty; // Will always return "something"
}
}
Blog/Portfolio | Evolution Xtreme | DFG Design | DFG Hosting | CSS-Tricks | Stack Overflow | Paul Irish
Having lame problems with your code? Let us help by using a jsFiddle
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.
this will returnCode:<?php class db { public static $stat = null; public $nonstat = null; public function __construct( $con ) { if(!self::$stat) { self::$stat = 'static '.$con; echo "\n--- init STATIC!"; } if(!$this->nonstat) { $this->nonstat = 'non-static '.$con; echo "\n--- init non-STATIC!"; } } } echo '<pre>'; $db = new db(1); echo "\nHave static: " . db::$stat; echo "\nHave non-static: " . $db->nonstat; echo "\n========================"; $db1 = new db(2); echo "\nHave static: " . db::$stat; echo "\nHave non-static: " . $db1->nonstat; ?>
Code:--- 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).
Bookmarks