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
One way for calling the same method both statically and non-statically is using the magic methods __call and __callStatic .
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.
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.
class A { public function doSomething(){ //doing something. } } require_once 'A. class. php'; class B { //Call the method doSomething() from the class A. }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With