When to call class method directly?
<?php
Class::method();
?>
When to call class method after object instatiated?
<?php
$object = new Class();
$object->method();
?>
What are the differences between both of them?
::
scope resolution operator that is used for direct call static class methods without object
Class::method();
you can use class variables $this->...
in this method.
$object = new Class();
new
is create object of class and you can also use class variables from object
in simple way object is instance of class.
Methods which are defined as static those methods will be called directly. Like function1 is static so it will be called as
A::function1();
class A
{
public static function function1()
{
$a = "Hi";
return $a;
}
public function function2()
{
$a = "Hi";
return $a;
}
}
Where as second method is not static and it will be called on the object of class A like below
$object = new A();
$object->function2();
if you are making any class function static then you can access by using scope resolution operator like in 1st case.In case of static function $this
is not available inside function.
<?php
class Product
{
public static function method() //static function
{
echo "static function" ;
}
}
Product::method(); // we can make direct call
?>
while in 2nd case object is created and we are accessing class methods through objects.
$object = new Class();
$object->method();