[WEB] PHP '??' 연산자

Profile-exe·2021년 8월 19일
0

web

목록 보기
7/11
post-thumbnail

PHP를 이용한 게시판에서 페이징을 구현하려 했다. if문과 isset()을 사용해서 $page 변수의 값을 설정하는 코드였다.

IDEPhpStorm을 사용해 개발중인데, if문에 밑줄이 생기며 다음과 같은 메시지가 나왔다.

'if' can be replaced with '??' version

삼항연산자(?:)로 바뀌는줄 알았으나, ??라는 다른 연산자였다.

if (isset($_GET['page'])) {
    $page = $_GET['page'];
} else {
    $page = 1;
}

이 코드가

$page = $_GET['page'] ?? 1;

이렇게 바뀌었다. 처음 보는 연산자였는데, 무엇인지 알아보자.


Syntactic Sugar

Syntatic Sugar - Wikipedia

해당 연산자를 알기 전에 Syntatic Sugar에 대해 알아두면 좋다.

In computer science, syntactic sugar is syntax within a programming language that is designed to make things easier to read or to express.

말 그대로 읽기 쉽거나 표현하기 쉽게 만들어진 것이다. 이것을 사용하면 가독성이 좋아지거나 더 명확한 표현이 가능하다.

예를 들어 JavaScriptasyncawaitPromise객체를 간편하게 다룰 수 있는 API인데, 이것들을 Syntatic Sugar라고 할 수 있다.

오늘 다룰 ?? 연산자도 Syntatic Sugar에 속한다.


Null coalescing operator

Null coalescing operator - PHP document

?? 연산자를 Null coalescing operator 즉, null 병합 연산자 라고 한다.

The null coalescing operator (??) has been added as syntactic sugar for the common case of needing to use a ternary in conjunction with isset(). It returns its first operand if it exists and is not null; otherwise it returns its second operand.

<?php
// Fetches the value of $_GET['user'] and returns 'nobody'
// if it does not exist.
$username = $_GET['user'] ?? 'nobody';

// This is equivalent to:
$username = isset($_GET['user']) ? $_GET['user'] : 'nobody';

// Coalescing can be chained: this will return the first
// defined value out of $_GET['user'], $_POST['user'], and
// 'nobody'.
$username = $_GET['user'] ?? $_POST['user'] ?? 'nobody';
?>

간단히 정리하자면 isset()이 사용되는 삼항연산자 표현식으로 변경이 가능한 코드는 ??연산자로 표현할 수 있다는 것이다.

??연산자 replace 알림이 뜬 코드는 다음과 같다.

if (isset($_GET['page'])) {
    $page = $_GET['page'];
} else {
    $page = 1;
}

이 코드를 삼항연산자로 표현한다면

$page = isset($_GET['page']) ? $_GET['page'] : 1;

이것을 다시 ?? 연산자로 표현하면

$page = $_GET['page'] ?? 1;

최종적으로 이 코드로 변환된다.


정리

  • isset()을 사용하는 삼항연산자로 표현 가능한 식은 ??로 간단하게 표현하자. => 가독성 ⬆

게시판 프로젝트 URL

Github - Profile-exe/CRUDboardsite

profile
컴퓨터공학과 학부생

0개의 댓글