Start networking and exchanging professional insights

Register now or log in to join your professional community.

Follow

Where Static methods are used?

user-image
Question added by Junaid Zameer , Web Deveoper , HyperTrade
Date Posted: 2014/01/08
George Dimitrov
by George Dimitrov , Unix System Administrator , ADVANCED.IO

Static methods and variables are useful when you want to share

information between objects of a class, or want to represent something

that's related to the class itself, not any particular object.

 

PHP allows you to access a non static method statically using '::', as well you cannot use $this in static method.

Syed Umair Akhtar
by Syed Umair Akhtar , System Controller , Toronto Transit Commission

A database connection would be a good use for a static function. You dont need direct access to an entire DB object, you just need access to the connection resource. So you can call

$connection =newDatabaseConnection();StaticClass::setDatabase($connection); $result =StaticClass::getDatabaseConnection()->query();

But if you need access to the class for storage later or multiple instances of the same object, then you would not want to go static.

Your class also now lives in a global scope, so you can access it from any class, in any scope, anywhere in your codebase.

function getUsers(){ $users =StaticClass::getDatabaseConnection()->query('SELECT * FROM users');}

Bowsil Ameen
by Bowsil Ameen , Sharepoint Development officer / architect , Etihad Airways

If you want to understand static method first we need know what is static class

 

Static Class

1) Can only have static members( static variables, static methods..)

2) this class cannot be instantiated.

3) Class is sealed

 

example

 

 public static class Demo 

   {        public static String GetName(string name)  

      {

return "My Name is "  + name;         

        }

}

 

Static Method

 

we can use the static method by calling the class name ( Note Not by Instance of the class Name)

That means you can call the method without instancating  the class

 

example

I am using the above static class

 

Demo.GetName("Test);

 

Output  - > My name is Test

 

Hope this helps,

 

 

 

 

 

More Questions Like This