![]() ![]() ![]() What about chaining method calls with null coalescing operator? The answer is no, for this the null safe operator can be used. ![]() Which is the same as: $userId = isset($_REQUEST) ? (isset($_REQUEST) ? $_REQUEST : 0) : 0 The null coalescing operator can be chained to form complex expressions: $userId = $_REQUEST ? $_REQUEST ? 0 $city = $userObj->location->city ? 'No city' If we cast this array to an object, the same chaining technique can be used: In case the array key doesn’t exist it will simply return the right-hand side: $age = $user ? 'unidentified' // unidentifiedĪlso we can use it for nested array items in multi-dimensional arrays: $country = $user ? 'No country' // UK $city = $user ? 'No city' // No city Without using null coalescing operator we can do something like this: $username = isset($user) ? $user : 'Annonymous' īut with the null coalescing we can rewrite it like so: $username = $user ? 'Annonymous' // John Doe The null coalescing operator is very beneficial when checking items existence in arrays, consider this example: $user = [ If we assign a value to variable $check it will return the value of $check: $check = 'yes' If the condition is correct that it will return the value of the condition otherwise it will return the else part which in the example is ‘no’. This is a common expression in PHP, and for this the null coalescing operator we can shorten this expression as follows: $canLogin = $check ? 'no' // noĪs you see we omit the first side from the ternary expression and replaced the isset() call with the ? operator. The most common tasks when manipulating nulls is to check for variable existence, in PHP typically we tend to use something like PHP isset() function in a ternary expression: $canLogin = isset($check) ? "yes" : "no" Dealing with null values is a common aspect in any programming language, and in PHP also there are many cases where we have to check for null values. ![]()
0 Comments
Leave a Reply. |
Details
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |