PHP Static Properties and Null Coalescing Assignment Operator

preview_player
Показать описание
While optimizing Filament queries, I discovered a few interesting things about static keyword in PHP.

- - - - -
Support the channel by checking out my products:

- - - - -
Other places to follow:
Рекомендации по теме
Комментарии
Автор

I try to avoid holding state in static properties. To hold shared state, I use a singleton pattern (and that's about the only thing I'm using a singleton for). This allows for injecting the global state into whatever class/method needs it, even create a mockup for testing.

VKLuc
Автор

Please discuss the frequent use of the 'static' keyword, Is it fine to use it? If I want to use PHP swoole is there any impact because of this?

AhsanKhan
Автор

From my experience, using static variables can be really helpful, but be careful when using them in jobs. Their state persists until the worker is killed, which can lead to unexpected issues since the variables aren’t reset.

paubenet
Автор

wow, thank you! it's a great trick, when i need to use static methods

janospeter
Автор

I think the problem with ur first approach is that when a static method is called, there is no object instantiation so the __construct() is not called. So when the static method getNavigationBadge() is called, $leadCount is undefined. If u set "protected static int $leadCount = 0", you would get rid of the error, but getNavigationBadge would always show 0 since the code in the __construct to set the variable doesn't get executed. You can use static variables in the constructor, and their use case imo is for something like: how would you keep track of how many time an object is created? Here is an example:
<?php

class User
{
public static int $count = 0;
public function __construct()
{
self::$count++;
}
}

$userA = new User();
$userB = new User();
$userC = new User();
var_dump(User::$count); // 3

Hope it helps

matteoruda
Автор

Personally I don't use static variables at all because I'm not sure if they would interfere with Octane. Maybe caching the result would be an option instead of writing it to static member variables because in the Cache key you can distinguish between users to ensure that you don't show data from one user to another user.

michalehmann
Автор

for something like this i have used laravel 11''s once() helper function not long ago

exodusdev
Автор

My first rule is no static method on any class, based on experience where i need to refactor the static property, it messes up other functions.

fluxcaruso