Common Questions

What if we find a global in a static method?

Sometimes we will find that a static class method uses a global variable like so:

1 <?php
2 class Foo
3 {
4 static public function doSomething($baz)
5 {
6 global $bar;
7 // ... do something with $bar ...
8 }
9 }
10 ?>

This is a problem because there is no constructor to which we can move the global variable as a property. There are two options here.

The first option is to pass all the needed globals as parameters on the static method itself, thereby changing the signature of the method:

1 <?php
2 class Foo
3 {
4 static public function doSomething($bar, $baz)
5 {
6 // ... do something with $bar ...
7 }
8 }
9 ?>

We would then search the codebase for all uses of Foo::doSomething( and pass the ...

Get Modernizing Legacy Applications in PHP now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.