분류 | 게시판 |
베스트 |
|
유머 |
|
이야기 |
|
이슈 |
|
생활 |
|
취미 |
|
학술 |
|
방송연예 |
|
방송프로그램 |
|
디지털 |
|
스포츠 |
|
야구팀 |
|
게임1 |
|
게임2 |
|
기타 |
|
운영 |
|
임시게시판 |
|
Scalar type declarations come in two flavours: coercive (default) and strict. The following types for parameters can now be enforced (either coercively or strictly): strings (string), integers (int), floating-point numbers (float), and booleans (bool). They augment the other types introduced in PHP 5: class names, interfaces, array and callable.
<?php
// Coercive mode
function sumOfInts(int ...$ints)
{
return array_sum($ints);
}
var_dump(sumOfInts(2, '3', 4.1));
The above example will output:
int(9)
To enable strict mode, a single declare directive must be placed at the top of the file. This means that the strictness of typing for scalars is configured on a per-file basis. This directive not only affects the type declarations of parameters, but also a function's return type (see return type declarations, built-in PHP functions, and functions from loaded extensions.
Full documentation and examples of scalar type declarations can be found in the type declaration reference.
PHP 7 adds support for return type declarations. Similarly to argument type declarations, return type declarations specify the type of the value that will be returned from a function. The same types are available for return type declarations as are available for argument type declarations.
<?php
function arraysSum(array ...$arrays): array
{
return array_map(function(array $array): int {
return array_sum($array);
}, $arrays);
}
print_r(arraysSum([1,2,3], [4,5,6], [7,8,9]));
The above example will output:
Array ( [0] => 6 [1] => 15 [2] => 24 )
Full documentation and examples of return type declarations can be found in the return type declarations. reference.
The null coalesce operator (??) has been added as syntactic sugar for the common case of needing to use a ternary in conjunction withisset(). 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';
// Coalesces can be chained: this will return the first
// defined value out of $_GET['user'], $_POST['user'], and
// 'nobody'.
$username = $_GET['user'] ?? $_POST['user'] ?? 'nobody';
?>
The spaceship operator is used for comparing two expressions. It returns -1, 0 or 1 when $a is respectively less than, equal to, or greater than $b. Comparisons are performed according to PHP's usual type comparison rules.
<?php
// Integers
echo 1 <=> 1; // 0
echo 1 <=> 2; // -1
echo 2 <=> 1; // 1
// Floats
echo 1.5 <=> 1.5; // 0
echo 1.5 <=> 2.5; // -1
echo 2.5 <=> 1.5; // 1
// Strings
echo "a" <=> "a"; // 0
echo "a" <=> "b"; // -1
echo "b" <=> "a"; // 1
?>
Array constants can now be defined with define(). In PHP 5.6, they could only be defined with const.
<?php
define('ANIMALS', [
'dog',
'cat',
'bird'
]);
echo ANIMALS[1]; // outputs "cat"
?>
Support for anonymous classes has been added via new class. These can be used in place of full class definitions for throwaway objects:
<?php
interface Logger {
public function log(string $msg);
}
class Application {
private $logger;
public function getLogger(): Logger {
return $this->logger;
}
public function setLogger(Logger $logger) {
$this->logger = $logger;
}
}
$app = new Application;
$app->setLogger(new class implements Logger {
public function log(string $msg) {
echo $msg;
}
});
var_dump($app->getLogger());
?>
The above example will output:
object(class@anonymous)#2 (0) { }
Full documentation can be found in the anonymous class reference.
This takes a Unicode codepoint in hexadecimal form, and outputs that codepoint in UTF-8 to a double-quoted string or a heredoc. Any valid codepoint is accepted, with leading 0's being optional.
echo "\u{aa}";
echo "\u{0000aa}";
echo "\u{9999}";
The above example will output:
ª ª (same as before but with optional leading 0's) 香
Closure::call() is a more performant, shorthand way of temporarily binding an object scope to a closure and invoking it.
<?php
class A {private $x = 1;}
// Pre PHP 7 code
$getXCB = function() {return $this->x;};
$getX = $getXCB->bindTo(new A, 'A'); // intermediate closure
echo $getX();
// PHP 7+ code
$getX = function() {return $this->x;};
echo $getX->call(new A);
The above example will output:
1 1
This feature seeks to provide better security when unserializing objects on untrusted data. It prevents possible code injections by enabling the developer to whitelist classes that can be unserialized.
<?php
// converts all objects into __PHP_Incomplete_Class object
$data = unserialize($foo, ["allowed_classes" => false]);
// converts all objects into __PHP_Incomplete_Class object except those of MyClass and MyClass2
$data = unserialize($foo, ["allowed_classes" => ["MyClass", "MyClass2"]);
// default behaviour (same as omitting the second argument) that accepts all classes
$data = unserialize($foo, ["allowed_classes" => true]);
The new IntlChar class seeks to expose additional ICU functionality. The class itself defines a number of static methods and constants that can be used to manipulate unicode characters.
<?php
printf('%x', IntlChar::CODEPOINT_MAX);
echo IntlChar::charName('@');
var_dump(IntlChar::ispunct('!'));
The above example will output:
10ffff COMMERCIAL AT bool(true)
In order to use this class, the Intl extension must be installed.
Expectations are a backwards compatible enhancement to the older assert() function. They allow for zero-cost assertions in production code, and provide the ability to throw custom exceptions when the assertion fails.
While the old API continues to be maintained for compatibility, assert() is now a language construct, allowing the first parameter to be an expression rather than just a string to be evaluated or a boolean value to be tested.
<?php
ini_set('assert.exception', 1);
class CustomError extends AssertionError {}
assert(false, new CustomError('Some error message'));
?>
The above example will output:
Fatal error: Uncaught CustomError: Some error message
Full details on this feature, including how to configure it in both development and production environments, can be found in theexpectations section of the assert() reference.
Classes, functions and constants being imported from the same namespace can now be grouped together in a single use statement.
<?php
// Pre PHP 7 code
use some\namespace\ClassA;
use some\namespace\ClassB;
use some\namespace\ClassC as C;
use function some\namespace\fn_a;
use function some\namespace\fn_b;
use function some\namespace\fn_c;
use const some\namespace\ConstA;
use const some\namespace\ConstB;
use const some\namespace\ConstC;
// PHP 7+ code
use some\namespace\{ClassA, ClassB, ClassC as C};
use function some\namespace\{fn_a, fn_b, fn_c};
use const some\namespace\{ConstA, ConstB, ConstC};
?>
This feature builds upon the generator functionality introduced into PHP 5.5. It enables for a return statement to be used within a generator to enable for a final expression to be returned (return by reference is not allowed). This value can be fetched using the newGenerator::getReturn() method, which may only be used once the generator has finishing yielding values.
<?php
$gen = (function() {
yield 1;
yield 2;
return 3;
})();
foreach ($gen as $val) {
echo $val, PHP_EOL;
}
echo $gen->getReturn(), PHP_EOL;
The above example will output:
1 2 3
Being able to explicitly return a final value from a generator is a handy ability to have. This is because it enables for a final value to be returned by a generator (from perhaps some form of coroutine computation) that can be specifically handled by the client code executing the generator. This is far simpler than forcing the client code to firstly check whether the final value has been yielded, and then if so, to handle that value specifically.
Generators can now delegate to another generator, Traversable object or array automatically, without needing to write boilerplate in the outermost generator by using the yield from construct.
<?php
function gen()
{
yield 1;
yield 2;
yield from gen2();
}
function gen2()
{
yield 3;
yield 4;
}
foreach (gen() as $val)
{
echo $val, PHP_EOL;
}
?>
The above example will output:
1 2 3 4
The new intdiv() function performs an integer division of its operands and returns it.
<?php
var_dump(intdiv(10, 3));
?>
The above example will output:
int(3)
session_start() now accepts an array of options that override the session configuration directives normally set in php.ini.
These options have also been expanded to support session.lazy_write, which is on by default and causes PHP to only overwrite any session file if the session data has changed, and read_and_close, which is an option that can only be passed to session_start() to indicate that the session data should be read and then the session should immediately be closed unchanged.
For example, to set session.cache_limiter to private and immediately close the session after reading it:
<?php
session_start([
'cache_limiter' => 'private',
'read_and_close' => true,
]);
?>
The new preg_replace_callback_array() function enables code to be written more cleanly when using the preg_replace_callback() function. Prior to PHP 7, callbacks that needed to be executed per regular expression required the callback function to be polluted with lots of branching.
Now, callbacks can be registered to each regular expression using an associative array, where the key is a regular expression and the value is a callback.
Two new functions have been added to generate cryptographically secure integers and strings in a cross platform way: random_bytes() andrandom_int().
Previously, list() was not guaranteed to operate correctly with objects implementing ArrayAccess. This has been fixed.
출처 | http://php.net/manual/en/migration70.new-features.php |
죄송합니다. 댓글 작성은 회원만 가능합니다.
번호 | 제 목 | 이름 | 날짜 | 조회 | 추천 | |||||
---|---|---|---|---|---|---|---|---|---|---|
455 | 문명6이 나오려나 보군요. [4] | 니콜라테슬라 | 16/05/12 07:06 | 49 | 12 | |||||
454 | 불공격차트 그래픽카드별 [9] | 니콜라테슬라 | 15/12/14 21:39 | 135 | 3 | |||||
453 | 동자카 !!! [1] | 니콜라테슬라 | 15/12/12 17:59 | 31 | 0 | |||||
452 | 구글 세이프서치를 피해보자. [4] | 니콜라테슬라 | 15/12/12 14:52 | 142 | 4 | |||||
451 | 1990년 IBM-XT를 처음 조립해보고 [4] | 니콜라테슬라 | 15/12/11 12:27 | 85 | 0 | |||||
450 | 하앍!!! 급 뽐뿌가 오기 시작한다. [1] | 니콜라테슬라 | 15/12/10 07:22 | 115 | 0 | |||||
449 | 장... 장패드 [1] | 니콜라테슬라 | 15/12/09 12:31 | 125 | 0 | |||||
448 | 창고에서 보물 발견^^ [3] | 니콜라테슬라 | 15/12/08 21:11 | 48 | 0 | |||||
447 | 꿈꾸던 시스템을 완성했는데 [4] | 니콜라테슬라 | 15/12/05 06:38 | 134 | 0 | |||||
446 | 드뎌 빨코를 벗어납니드아!!!!! 감겨규ㅠ [9] | 니콜라테슬라 | 15/12/04 08:55 | 51 | 0 | |||||
▶ | php 7 릴리즈 됐슴돠. 속도 속도!!! [15] | 니콜라테슬라 | 15/12/03 07:18 | 75 | 2 | |||||
444 | 눈이 내리고 있습니다. | 니콜라테슬라 | 15/11/27 16:51 | 40 | 1 | |||||
443 | 요즘 바빠서 오유 온라인 할 시간이 없네요 흐규 흐규 [1] | 니콜라테슬라 | 15/11/13 13:58 | 33 | 0 | |||||
442 | 아마존 배송 잘못걸리니 장난아니게 느립니다. [1] | 니콜라테슬라 | 15/11/12 20:38 | 51 | 0 | |||||
441 | 낚시 좋아졌네요 ^^ [1] | 니콜라테슬라 | 15/11/06 08:57 | 46 | 0 | |||||
440 | 오랜만에 접했더니 너무 많이 바뀌었군요. [6] | 니콜라테슬라 | 15/10/13 11:44 | 54 | 0 | |||||
439 | Fable Legends베타에서 맥스웰은 비동기 컴퓨팅이 작동하지 않았다 | 니콜라테슬라 | 15/10/03 07:34 | 81 | 0 | |||||
438 | GNU가 뭐에요? [10] | 니콜라테슬라 | 15/09/26 09:40 | 62 | 1 | |||||
437 | ssd 산지얼마 안됐는데 또 뽐뿌가 ㄷㄷ [6] | 니콜라테슬라 | 15/09/25 03:18 | 164 | 1 | |||||
436 | Love is Free [8] | 니콜라테슬라 | 15/09/25 02:49 | 239 | 11 | |||||
435 | [벤치]DX12 Fable Legends [3] | 니콜라테슬라 | 15/09/25 01:48 | 70 | 2 | |||||
434 | 정치인들과의 만찬대신 노숙자들과의 식사를 선택한 교황 [2] | 니콜라테슬라 | 15/09/23 12:37 | 162 | 6 | |||||
433 | 수능(SAT)문제를 풀어주는 인공지능 시스템 [5] | 니콜라테슬라 | 15/09/23 09:26 | 116 | 1 | |||||
432 | 파스칼이 파운드리에서 이미 만들어졌다. [6] | 니콜라테슬라 | 15/09/22 20:19 | 86 | 2 | |||||
431 | 볼타는 2018년에 나오는군요 [6] | 니콜라테슬라 | 15/09/22 20:04 | 113 | 1 | |||||
430 | 19]싸움에서 이기는 법 [4] | 니콜라테슬라 | 15/09/19 02:17 | 317 | 12 | |||||
429 | 노트북에 내장 그래픽밖에 없다고? [6] | 니콜라테슬라 | 15/09/18 21:14 | 102 | 1 | |||||
428 | 윈 10 2016년의 컨셉 [4] | 니콜라테슬라 | 15/09/18 11:23 | 237 | 1 | |||||
427 | 허세어의 수냉 980Ti [3] | 니콜라테슬라 | 15/09/17 10:45 | 168 | 0 | |||||
426 | iTunes가 업뎃되네요 | 니콜라테슬라 | 15/09/17 08:59 | 83 | 0 | |||||
|
||||||||||
[1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [다음10개▶] | ||||||||||