Home > headlines > body text

How to write different PHP?

Guanhui
Release: 2020-07-23 13:05:31
forward
3244 people have browsed it

How to write different PHP?

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";
}
Copy after login

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([
            &#39;plateNumber&#39; => &#39;required|alpha_num|min:3|max:20|unique:users,plate_number&#39;,
            &#39;email&#39; => &#39;required|email|unique:users&#39;,
            &#39;firstName&#39; => &#39;required|alpha&#39;,
            &#39;lastName&#39; => &#39;required|alpha&#39;,
            &#39;password&#39; => &#39;required|min:8&#39;,
            &#39;phone&#39; => &#39;required|numeric|unique:users&#39;
        ]);
        // Create user
        $new_user = new User;
        $new_user->plate_number = trim(strtoupper($request->input(&#39;plateNumber&#39;)));
        $new_user->email = trim($request->input(&#39;email&#39;));
        $new_user->first_name = trim($request->input(&#39;firstName&#39;));
        $new_user->last_name = trim($request->input(&#39;lastName&#39;));
        $new_user->password = Hash::make($request->input(&#39;password&#39;));
        $new_user->phone = trim($request->input(&#39;phone&#39;));
        $new_user->save();
        return response()->json([
            &#39;success&#39; => true,
        ]);
    }
}
Copy after login

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 = &#39;adult&#39;;
} else {
    $type = &#39;not adult&#39;;
}
Copy after login

You can use the ternary operator The notation simplifies this code to the following:

<?php
$age = 17;
$type = $age >= 18 ? &#39;adult&#39; : &#39;not adult&#39;;
Copy after login

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 = &#39;http://example.com/api&#39;;
$base_url = $url ? $url : &#39;http://localhost&#39;;
Copy after login

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 = &#39;http://example.com/api&#39;;
$base_url = $url ?: &#39;http://localhost&#39;;
Copy after login

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 ?? &#39;http://localhost&#39;;
Copy after login

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 ?? &#39;http://localhost&#39;;
Copy after login

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 = &#39;http://example.com&#39;;
$base_url = $base_url ?? &#39;http://localhost&#39;;
Copy after login

You can shorten it using the null merge assignment operator This code

<?php
$base_url = &#39;http://example.com&#39;;
$base_url ??= &#39;http://localhost&#39;;
Copy after login

All these nall merging techniques can be implemented on array values.

<?php
$my_array = [
    &#39;first_name&#39; => &#39;Adnan&#39;,
    &#39;last_name&#39; => &#39;Babakan&#39;
];
$my_array[&#39;first_name&#39;] ??= &#39;John&#39;;
$my_array[&#39;age&#39;] ??= 20;
Copy after login

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
Copy after login

Simple but very useful.

This gets even more interesting when you realize that spaceship operators can also compare other things:

<?php
// String
echo &#39;c&#39; <=> &#39;b&#39;; // result: -1
// String case
echo &#39;A&#39; <=> &#39;a&#39;; // result: 1
// Array
echo [5, 6] <=> [2, 7]; // result: 1
Copy after login

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);
Copy after login

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);
Copy after login

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);
Copy after login

As you can see it's very simple and neat and has access to the global scope by default.

Recommended tutorial: "PHP"

Related labels:
php
source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!