Please any one tell me difference between static and non static class and method.
<?php
class a
{
public static function sum($a,$b)
{
return $a+$b;
}
}
$obj = new a();
echo $obj->sum(20,30);
echo $c=a::sum(10,10);
?>
Please any one tell me difference between static and non static class and method.
<?php
class a
{
public static function sum($a,$b)
{
return $a+$b;
}
}
$obj = new a();
echo $obj->sum(20,30);
echo $c=a::sum(10,10);
?>
A static method is the same for every instance of a class. It is attached to the class itself. A non-static (instance) method is attached to an object, an instance of a class. The functional difference is that an instance method has access to instance properties, whereas a static method does not, because it exists at the class level.
Here is an extract from PHP Manual
Declaring class properties or methods as static makes them accessible without needing an instantiation of the class.
A property declared as static cannot be accessed with an instantiated class object (though a static method can).
Static functions, by definition, cannot and do not depend on any instance properties of the class. That is, they do not require an instance of the class to execute. In some sense, this means that the function doesn't (and will never need to) depend on members or methods (public or private) of the class.
My code is not php. It's more of a generic representation.
Let's say you want to find sine of a number. You'd mostly likely rely on built in math library by doing something like Math.sine(30)
. You see how I accessed the method sine inside the Math class without creating an instance of the Math class. These methods are static methods. If sine was not a static method then I'd have to do something like
Math m = new Math(); // create instance
m.sine(30); // call instance method
And for static method
Math.sine(30) // static call