본문 바로가기

Code Snippets/php

What's New in PHP 5.4

이번에 PHP5.3을 5.4로 업그레이드 하면서 지금 PHP7이 출시된 시점에 이제서야 다루지만...

사라진 기능들

break/continue에서 변수를 사용할 수 없다

$two = 2;
 
while (true) {
    while (true) {
        break $two;
    }
}
PHP Fatal error: 'break' operator with non-constant operand is no longer supported in test.php on line 6

잠재적으로 위험한 자동 전역변수 기능 제거

  • PHP 5.3에서 Deprecated 되었고 5.4 부터는 제거되었다.
  • php.ini 파일에서 register_globalsregister_long_arrays 지시자가 사라지고 import_request_variables() 함수가 사라졌다.

함수 인자에 변수를 참조로 전달할 수 없게됨

function modify($array) {
    $array[] = 'zero';
}
 
$array array(0, 1, 2);
 
modify(&$array);
PHP Fatal error:  Call-time pass-by-reference has been removed; If you would like to pass argument by reference, modify the declaration of modify(). in test.php on line 8

위와 같이 함수를 호출하는 시점에서 레퍼런스를 넘길 수 없다.

function modify(&$array) {
    $array[0] = 'zero';
}
 
$array array(0, 1, 2);
 
modify($array);

인자를 레퍼런스로 받도록 함수를 선언해야 한다.

따옴표 등 자동 이스케이핑 기능 제거

  • php.ini 파일에서 magic_quotes_gpcmagic_quotes_runtimemagic_quotes_sybase 지시자가 사라졌다.
  • get_magic_quotes_gpc()get_magic_quotes_runtime() 함수는 남아있지만 무조건 false 값을 리턴하고set_magic_quotes_runtime() 함수는 E_CORE_ERROR 에러를 발생시킨다.

타임존 관련 기능 제거

putenv('TZ=Asia/Seoul');

위와 같이 타임존을 세팅할 수 없다. date_default_timezone_set() 함수를 사용해야 한다.

또한 php.ini 에서 date.timezone 지시자를 세팅하지 않거나 date_default_timezone_set() 함수로 타임존을 세팅하지 않았을 때 타임존을 알아서 설정하는 기능이 제거되었다. 이러한 경우는 무조건 UTC로 설정된다.

제거된 PECL 익스텐션

ext/sqlite 익스텐션이 제거되었다. ext/sqlite3, ext/pdo_sqlite 익스텐션은 계속 사용 가능하다.

기본 문법 등 개선

배열 선언 문법의 추가

$array1 array(1, 2, 3);   // old syntax
$array2 = [1, 2, 3];        // new syntax
 
var_dump($array1 == $array2);   //=> bool(true)

다른 많은 언어들 처럼 대괄호를 사용해 배열을 선언할 수 있다.

2진수 표현 문법 추가

var_dump(0b001010); //=> int(10)

Class::{expr}() 호출 가능

class Test {
    public function hello() {
        echo "Hello\n";
    }
}
 
function getMethodName() {
    return 'hello';
}
 
Test::{getMethodName()}();

멀티바이트 언어 지원

기존에는 PHP 컴파일시 --enable-zend-multibyte 옵션을 주어야 했지만 이제는 기본으로 enable 되어 있다. php.ini 에서 zend.multibyte 지시자로 끌 수도 있다.

Traits 지원

trait Hello {
    public function sayHello() {
        echo "Hello\n";
    }
}
 
trait Bye {
    public function sayBye() {
        echo "Bye\n";
    }
}
 
class Test {
    use Hello, Bye;
}
 
$test new Test();
$test->sayHello();      //=> Hello
$test->sayBye();        //=> Bye

클로져에서 $this 사용

class Test1 {
    public $value "I'm Test1";
    public function getClosure($property) {
        return function() use ($property) {
            return $this->$property;
        };
    }
}
 
class Test2 {
    public $value "I'm Test2";
    public function test() {
        $test new Test1();
        $function $test->getClosure('value');
        echo $function(), "\n";
    }
}
 
$class new Test2();
$class->test(); //=> I'm Test1

배열의 역참조

function test() {
    return array(1, 2, 3);
}
 
echo test()[1]; //=> 2

타입 힌트에 Callable 추가

function test(Callable $callback$value) {
    return $callback($value);
}
 
$callback function($value) { echo "$value\n"; };
 
test($callback'Hello');
test('String''Hello');
Hello
PHP Catchable fatal error:  Argument 1 passed to test() must be callable, string given, called in test.php on line 9 and defined in test.php on line 2

배열 값으로 함수를 호출하기

class Test {
    public static function hello() {
        echo "Hello\n";
    }
}
 
$function array('Test''hello');
$function();

클래스 초기화와 동시에 메소드 호출

class Test {
    public function method() {
        echo "Hello\n";
    }
}
 
(new Test())->method(); //=> Hello

<?=

php.ini 파일의 short_open_tag 설정과는 상관 없이 <?= 문법은 항상 사용 가능하다

클로져를 다른 오브젝트에 바인딩 시키기

class Test1 {
    public $value "I'm Test1";
    public function getClosure($property) {
        return function() use ($property) {
            return $this->$property;
        };
    }
}
 
class Test2 {
    public $value "I'm Test2";
    public function test() {
        $test new Test1();
        $function $test->getClosure('value');
        $function $function->bindTo($this);
        echo $function(), "\n";
    }
}
 
$class new Test2();
$class->test(); //=> I'm Test2

타입 캐스팅

  • NULL, 빈 문자열, FALSE 값이 Object 타입으로 캐스팅 될 때 Warning 메시지가 발생된다.
  • 배열이 String 타입으로 캐스팅 될 때 Notice 메시지가 발생한다.

php.ini 지시자의 변경

default_charset

기본 값이 ISO-8859-1에서 UTF-8으로 변경되었다.

error_reporting

E_ALL 값은 E_STRICT를 포함한다.

기본 함수 등 개선

hex2bin() 함수 추가

echo hex2bin('6578616d706c65206865782064617461'); //=> example hex data

number_format()

$dec_point='.'$thousands_sep=',' 인자가 추가됨.

정렬 함수들

sortrsortksortkrsortasortarsortarray_multisort 함수들에 SORT_NATURALSORT_FLAG_CASE 옵션이 추가되었다.

array_combine()

빈 배열 두 개를 인자로 받을 경우 FALSE 대신 빈 배열을 리턴한다.

$_SERVER['REQUEST_TIME_FLOAT']

요청 시각을 마이크로초 단위로 돌려주는 $_SERVER['REQUEST_TIME_FLOAT'] 변수가 추가되었다.

간단한 웹서버가 내장됨

php -S 127.0.0.1:8080 -t /var/www

익스텐션 관련 변경

CURL

전송 속도를 제어할 수 있는 CURLOPT_MAX_RECV_SPEED_LARGECURLOPT_MAX_SEND_SPEED_LARGE 옵션이 추가 되었다.

File System

scandir() 정렬 옵션에 SCANDIR_SORT_NONE 값이 추가됨.

JSON

JsonSerializable 인터페이스가 추가되었다.

json_encode()

JSON_BIGINT_AS_STRINGJSON_PRETTY_PRINTJSON_UNESCAPED_SLASHESJSON_UNESCAPED_UNICODE 옵션이 추가됨.

json_decode()

$options=0 파라미터가 추가되어 JSON_BIGINT_AS_STRING 옵션을 사용 가능.

MySQL

ext/mysql, mysqli, pdo_mysql 익스텐션이 기본으로 mysqlnd를 사용한다.

PREG

preg_match_all() 함수에서 세 번째 인자($matches)를 생략해도 된다.

Session

<form action="upload.php" method="POST" enctype="multipart/form-data">
    <input type="hidden" name="<?=ini_get("session.upload_progress.name")?>" value="attachments"/>
    <input type="file" name="file1"/>
    <input type="submit"/>
</form>

위와 같은 폼으로 업로드를 하고 $_SESSION['upload_progress_attachments'] 값을 통해 업로드 상태를 파악할 수 있다.

'Code Snippets > php' 카테고리의 다른 글

그누보드 관리자에서 포스트 등록관리  (0) 2018.08.08
함수 : set_time_limit  (0) 2015.12.11
함수 : error_reporting  (0) 2015.12.11
함수 : array_key_exists  (0) 2015.12.10
함수 : ucfirst / lcfirst  (0) 2015.12.08