Experienced developers often advise avoiding static methods in PHP classes. In this tutorial, let me give you a few practical Laravel/PHP examples behind this advice. When are static methods ok, and when it's best to avoid them?
Independent Static Methods in Simple Classes Are OK
Let's start with an example where static methods can be absolutely fine. Imagine the Controller that uses a Service to store data:
use App\Services\PropertyService;use App\Http\Requests\StorePropertyRequest; class PropertyController extends Controller{ public function store(StorePropertyRequest $request) { PropertyService::store($request->validated()); // ... more logic and return }}
Why couldn't that store()
method in the service be static? It can be!
app/Services/PropertyService.php:
namespace App\Services; use App\Models\Property; class PropertyService { public static function store(array $propertyData): Property { $property = Property::create($propertyData); // ... maybe some more logic return $property; } }
And you know what? This code is totally fine. There's absolutely nothing wrong in using a Static method here because it's "stateless" - it doesn't depend on any other classes or parameters: it just gets the data and stores it in the DB.
So, on the surface, it's ok to use static methods for very simple examples.
Until the code logic grows, and static becomes "not cool anymore".
What if Static Method Needs CLASS PARAMETERS?
Now, let's imagine that the service PropertyService
should be initialized with some parameter(s). For example, a city name which would later help in geolocation, in multiple methods of that class.
We would do that with the PHP 8 syntax of...