Skip to content
Advertisement

Accessing a public/private function inside a static function?

Due to the fact that you can not use $this-> inside a static functio, how are you supposed to access regular functions inside a static?

JavaScript

This throws an error, because you can’t use $this-> inside a static.

JavaScript

This throws the following error:

JavaScript

How can you access regular methods inside a static method? In the same class*

Advertisement

Answer

Static methods can only invoke other static methods in a class. If you want to access a non-static member, then the method itself must be non-static.

Alternatively, you could pass in an object instance into the static method and access its members. As the static method is declared in the same class as the static members you’re interested in, it should still work because of how visibility works in PHP

JavaScript

Do note though, that just because you can do this, it’s questionable whether you should. This kind of code breaks good object-oriented programming practice.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement