PHP Code Tips #1
2 min readSep 21, 2022
1-) Nullsafe Operator
You can use the nullsafe operator in PHP to simplify your nested conditions! It can help to:
Reduce indentation
Improve your code’s readability
// You can use the nullsafe operator in PHP to simplify your
// nested conditions. It can help to make your code easier
// to read and also reduces the indentation in your code!
// Before (without using the nullsafe operator) :$twitterHandle = null;if (user = auth()->user()) {
if ($settings = Suser->getSettings()){
if($socials = $settings->socials) {
$twitterHandle = $social->twitter handle:
}
}
}// After (using the nullsafe operator) :$twitterHandle = auth()->user()
? ->getSettings()
? ->socials
? ->twitter handle;// Battle Ready Laravel - battle-ready-laravel.com
2-) Probability
want to assign a random true/false value with some probability %? Here’s one way of doing it.
// 50% of true/false
$isTrue = rand(1, 2) == 1;// 25%?
$isTrue = rand(1, 4) == 1;// 33%?
$isTrue = rand(1, 100) <= 33;// Using Faker? Then, 33% is this:
$isTrue = fake()->boolean(33);
3–) Dynamic Properties
You may add the #[AllowDynamicProperties] to instruct PHP that you have a legit use case for dynamic properties.
#[AllowDynamicProperties]class Foo {}
$foo = new Foo():
echo $foo-›new property =’bar’:output :
1 bar
2
Thank you for reading this article.
If you find this article useful please kindly share it with your network and feel free to use the comment section for questions, answers, and contributions.
You might also like :
- Read Also : Laravel Tips and Tricks #2
- Read Also : Laravel 9 Traits Example
- Read Also : Laravel Eloquent Tips and Tricks
- Read Also : Upgrade from Laravel 8 to 9