Kanishka Panamaldeniya
Kanishka Panamaldeniya

Reputation: 17586

Call to a non static method with out creating an object works fine in PHP

I am doing a PHP tutorial and I found this code

Class Insurance
{
   function clsName()
   {
      echo get_class($this)."\n";
   }
}


$cl = new Insurance();
$cl->clsName();
Insurance::clsName();

here function clsName() is accessed without creating an instance of Insuarance

Insurance::clsName();

But from the definition

The Scope Resolution Operator (also called Paamayim Nekudotayim) or in simpler terms, the double colon, is a token that allows access to static, constant, and overridden properties or methods of a class.

When referencing these items from outside the class definition, use the name of the class.

http://php.net/manual/en/language.oop5.paamayim-nekudotayim.php

I searched in web but coul not find a good explanation why this code is working? please explain.

Upvotes: 0

Views: 152

Answers (1)

Bang
Bang

Reputation: 929

When I run it with error reporting E_ALL :

Insurance
<br />
<b>Strict Standards</b>:  Non-static method Insurance::clsName() should not be called statically in <b>[...][...]</b> on line <b>12</b><br />
<br />
<b>Notice</b>:  Undefined variable: this in <b>[...][...]</b> on line <b>5</b><br />
Insurance

Now the question is why it still working ? as you can see, "Insurance" was displayed.

When you do echo get_class($this)."\n"; when you call in a static context, PHP will run it like echo get_class(null)."\n";.

And if you read the behavior of get_class http://php.net/manual/en/function.get-class.php, The class is recognized because the function was call inside the class.

Upvotes: 1

Related Questions