Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling non-static method with double-colon(::)

Tags:

php

static

Why can't I use a method non-static with the syntax of the methods static(class::method) ? Is it some kind of configuration issue?

class Teste {      public function fun1() {         echo 'fun1';     }     public static function fun2() {         echo "static fun2" ;     } }  Teste::fun1(); // why? Teste::fun2(); //ok - is a static method 
like image 779
NakaBr Avatar asked Sep 20 '10 19:09

NakaBr


People also ask

How do you call a non static method statically?

One way for calling the same method both statically and non-statically is using the magic methods __call and __callStatic .

Can we call non static method in same class?

Similarly, a private static method can be called from a non-static method of the same class but a public static method e.g. main() can be called from anywhere.

How do you call a non static method from another method in Java?

But when we try to call Non static function i.e, TestMethod() inside static function it gives an error - “An object refernce is required for non-static field, member or Property 'Program. TestMethod()”. So we need to create an instance of the class to call the non-static method.

How can call non static method from another class in PHP?

class A { public function doSomething(){ //doing something. } } require_once 'A. class. php'; class B { //Call the method doSomething() from the class A. }


1 Answers

PHP is very loose with static vs. non-static methods. One thing I don't see noted here is that if you call a non-static method, ns statically from within a non-static method of class C, $this inside ns will refer to your instance of C.

class A  {     public function test()     {         echo $this->name;     } }  class C  {      public function q()      {          $this->name = 'hello';          A::test();      } }  $c = new C; $c->q();// prints hello 

This is actually an error of some kind if you have strict error reporting on, but not otherwise.

like image 130
davidtbernal Avatar answered Sep 24 '22 21:09

davidtbernal