ابدأ بالتواصل مع الأشخاص وتبادل معارفك المهنية

أنشئ حسابًا أو سجّل الدخول للانضمام إلى مجتمعك المهني.

متابعة

Where Static methods are used?

user-image
تم إضافة السؤال من قبل Junaid Zameer , Web Deveoper , HyperTrade
تاريخ النشر: 2014/01/08
George Dimitrov
من قبل 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
من قبل 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
من قبل 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,

 

 

 

 

 

المزيد من الأسئلة المماثلة