PHP is one of the most discussed programming languages in the development world. Some call it an ineffective programming language, some call it an annoying programming language with no conventions or architecture, and I agree with some of them because they have fair points. However, here I will share my experience of programming with PHP over the years. Some of these tricks are only available in the latest PHP versions, so they may not work in older versions.
Type hints and return types
PHP is not a perfect language as far as data types are concerned, but you can use type hints and return types to improve your code quality and prevent further type conflicts. Not many people use these features of PHP, and not all PHP programmers know that this is possible.
<?php function greet_user(User $user, int $age): void { echo "Hello" . $user->first_name . " " . $user->last_name; echo "\nYou are " . $age . " years old"; }
Type hints can be declared using the name or class of the type before the parameter variables and the return type after the function signature after the colon.
You can use this in a more advanced way when designing controllers in a framework like Laravel:
<?php class UserController extends Controller { // User sign up controller public function signUp(Request $request): JsonResponse { // Validate data $request->validate([ 'plateNumber' => 'required|alpha_num|min:3|max:20|unique:users,plate_number', 'email' => 'required|email|unique:users', 'firstName' => 'required|alpha', 'lastName' => 'required|alpha', 'password' => 'required|min:8', 'phone' => 'required|numeric|unique:users' ]); // Create user $new_user = new User; $new_user->plate_number = trim(strtoupper($request->input('plateNumber'))); $new_user->email = trim($request->input('email')); $new_user->first_name = trim($request->input('firstName')); $new_user->last_name = trim($request->input('lastName')); $new_user->password = Hash::make($request->input('password')); $new_user->phone = trim($request->input('phone')); $new_user->save(); return response()->json([ 'success' => true, ]); } }
Ternary Operator
The ternary operator is something that almost 70% of programmers know and use extensively, but if you don’t know what the ternary operator is, here is an example:
<?php $age = 17; if($age >= 18) { $type = 'adult'; } else { $type = 'not adult'; }
You can use the ternary operator The notation simplifies this code to the following:
<?php $age = 17; $type = $age >= 18 ? 'adult' : 'not adult';
If the condition is met, the second part is not assigned to the variable.
There is also a shorter way if you want to use the value of the condition if it evaluates to a true value.
<?php $url = 'http://example.com/api'; $base_url = $url ? $url : 'http://localhost';
As you can see $url, is used both as a condition and as a result if the condition is true. In this case, the left-hand operand can be escaped:
<?php $url = 'http://example.com/api'; $base_url = $url ?: 'http://localhost';
Null Coalescing Operator
Just like the ternary operator, you can use Null coalescing operator to see if the value exists. Note that because false itself is the value, the existing value is different from the error value.
<?php $base_url = $url ?? 'http://localhost';
Now $base_url is equal to, http://localhost but if we define $url as false, the $base_url variable will be equal to false.
<?php $url = false; $base_url = $url ?? 'http://localhost';
Using this operator you can check if a variable has been defined before and if it has not been assigned a value:
<?php $base_url = 'http://example.com'; $base_url = $base_url ?? 'http://localhost';
You can shorten it using the null merge assignment operator This code
<?php $base_url = 'http://example.com'; $base_url ??= 'http://localhost';
All these nall merging techniques can be implemented on array values.
<?php $my_array = [ 'first_name' => 'Adnan', 'last_name' => 'Babakan' ]; $my_array['first_name'] ??= 'John'; $my_array['age'] ??= 20;
The above array will have first_nameas, Adnan because it is already defined, but will define a new key named age and give it the number 20 because it does not exist.
Spaceship Operator
The spaceship operator is useful when you want to know which operand is larger rather than just knowing if one side is larger. operator.
The spaceship operator will return a value of 1, 0 or -1 when the left operand is larger, when the two operands are equal, and when the right operand is larger respectively.
<?php echo 5 <=> 3; // result: 1 echo -7 <=> -7; // result: 0 echo 9 <=> 15; // result: -1
Simple but very useful.
This gets even more interesting when you realize that spaceship operators can also compare other things:
<?php // String echo 'c' <=> 'b'; // result: -1 // String case echo 'A' <=> 'a'; // result: 1 // Array echo [5, 6] <=> [2, 7]; // result: 1
Arrow Functions
If you have ever written a JavaScript application, especially using its latest versions, you should be familiar with arrow functions. Arrow functions are a shorter way of defining functions without scope.
<?php $pi = 3.14; $sphere_volume = function($r) { return 4 / 3 * $pi * ($r ** 3); }; echo $sphere_volume(5);
The above code will throw an error because $pi is not a variable defined within the scope of this particular function. If we want to use it, we should change our function slightly:
<?php $pi = 3.14; $sphere_volume = function($r) use ($pi) { return 4 / 3 * $pi * ($r ** 3); }; echo $sphere_volume(5);
So now our function can use the $pi variable defined in the global scope.
But a shorter way to do these things is to use arrow functions.
<?php $pi = 3.14; $sphere_volume = fn($r) => 4 / 3 * $pi * ($r ** 3); echo $sphere_volume(5);
As you can see it's very simple and neat and has access to the global scope by default.
Recommended tutorial: "PHP"