2

I wrote a code like this

class B
{
   public static function test() {
   echo "Static function called<br/>";
   }
}

B::test();
$ob = new B();
$ob->test();

I read many article, static function is called using :: operator But i can call test function using object initialization and :: operator what is the difference? Please explain

Anish Chandran
  • 427
  • 1
  • 5
  • 19
  • PHP is very forgiving. What you're doing may trigger an `E_STRICT` level warning however you probably don't have your `error_reporting` set to include those – Phil Oct 06 '16 at 06:49
  • @Phil it can be totally different. you can get even fatal error. – ICE Oct 06 '16 at 08:00
  • You can do `$ob::test()` as a shorthand/alternative to `B::test()`, the result is the same. `$ob->test()` appears to be another shorthand for the same thing. As long as the method is decorated with `static`, the result is always the same. See http://stackoverflow.com/a/39890523/476 – deceze Oct 06 '16 at 08:05

1 Answers1

0

It's different. When you are using :: it means you are dealing directly with class. when you are using -> you are dealing with object. I change your sample to show you how it works:

class B
{
   private static $var;

   public static function test() {
      echo self::$var."Static function called<br/>";
   }

   public static function change($value)
   {
    self::$var = $value;
   }
}

B::test();
$ob = new B();
$ob->test();
$ob->change(10);
B::test();

the result will be:

Static function called
Static function called
10Static function called

because the first time static $var doesn't have anything in it. it shows just string. after creating $ob object we changed STATIC $var to 10. and after that because it was STATIC, when you are using :: again, you can see that static var changed.

now see another example:

class B
{
   private static $var;

   public function test() {
      echo self::$var."function called<br/>";
   }

   public function change($value)
   {
    self::$var = $value;
   }
}

B::test();
$ob = new B();
$ob->test();
$ob->change(10);
B::test();

The result will be:

function called
function called
10function called

because as i said before, :: means you are directly dealing with class.

now see another example:

class B
{
   private $var;

   public function test() {
      echo $this->var."function called<br/>";
   }

   public function change($value)
   {
    $this->$var = $value;
   }
}

$ob = new B();
$ob->test();
$ob->change(10);
B::test();

the result will be:

function called
Fatal error: Uncaught Error: Cannot access empty property

When you create $ob you have object. when you are using :: you can not have $var inside test or change method. because they have $this-> in it and it means they are dealing with object.

and when you know these, you know when and how must use :: or ->

ICE
  • 1,667
  • 2
  • 21
  • 43