Inscrivez-vous ou connectez-vous pour rejoindre votre communauté professionnelle.
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.
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');}
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,