strict type은 PHP에서 무엇을 합니까?
나는 PHP 7에서 다음과 같은 새로운 행을 보았지만, 아무도 그것이 무엇을 의미하는지 설명해주지 않는다.구글에서 검색해 봤는데, 여론 조사 같은 걸 할 수 있을까 말까 하는 얘기밖에 안 해요.
declare(strict_types = 1);
그게 뭘 하는데?코드에 어떤 영향을 미칩니까?내가 할까?
설명 좀 해주시면 좋을 것 같아요.
Treehouse 블로그에서 :
PHP 7에서는 스칼라 타입이 추가되었습니다.구체적으로는 int, float, string 및 bool입니다.
스칼라 타입의 힌트를 추가하고, 엄격한 요건을 유효하게 함으로써, 보다 정확하고 자기 문서화된 PHP 프로그램을 작성할 수 있을 것으로 기대된다.또한 코드를 더 잘 제어할 수 있고 코드를 더 쉽게 읽을 수 있습니다.
기본적으로는 스칼라 타입 선언은 엄격하지 않습니다.즉, 원래 타입을 type-declaration으로 지정된 타입과 일치하도록 변경하려고 합니다.즉, 숫자로 시작하는 문자열을 플로트가 필요한 함수에 전달하면 처음부터 숫자를 잡고 다른 모든 것을 제거합니다.int가 필요한 함수에 플로트를 전달하면 int(1)가 됩니다.
기본적으로는 PHP는 가능한 경우 잘못된 유형의 값을 예상 스칼라 유형에 캐스팅합니다.예를 들어, 문자열이 예상되는 파라미터에 대해 정수가 지정된 함수는 문자열 유형의 변수를 가져옵니다.
엄밀한 유형 비활성화(평가):
<?php
function AddIntAndFloat(int $a, float $b) : int
{
return $a + $b;
}
echo AddIntAndFloat(1.4, '2');
/*
* without strict typing, PHP will change float(1.4) to int(1)
* and string('2') to float(2.0) and returns int(3)
*/
파일 단위로 strict 모드를 이노블로 할 수 있습니다.strict 모드에서는 유형 선언의 정확한 유형의 변수만 허용되거나 TypeError가 느려집니다.이 규칙의 유일한 예외는 플로트를 예상하는 함수에 정수를 지정할 수 있다는 것입니다.내부 함수 내의 함수 호출은 strict_types 선언의 영향을 받지 않습니다.
strict 모드를 이노블로 만들려면 declarate 문이 strict_types 선언과 함께 사용됩니다.
엄밀한 타입이 유효(평가판):
<?php declare(strict_types=1);
function AddIntAndFloat(int $a, float $b): int
{
return (string) $a + $b;
}
echo AddIntAndFloat(1.4,'2');
// Fatal error: Uncaught TypeError: Argument 1 passed to AddIntAndFloat() must be of the type int, float given
echo AddIntAndFloat(1,'2');
// Fatal error: Uncaught TypeError: Argument 2 passed to AddIntAndFloat() must be of the type float, string given
// Integers can be passed as float-points :
echo AddIntAndFloat(1,1);
// Fatal error: Uncaught TypeError: Return value of AddIntAndFloat() must be of the type integer, string returned
작업 예:
<?php
declare(strict_types=1);
function AddFloats(float $a, float $b) : float
{
return $a+$b;
}
$float = AddFloats(1.5,2.0); // Returns 3.5
function AddFloatsReturnInt(float $a, float $b) : int
{
return (int) $a+$b;
}
$int = AddFloatsReturnInt($float,1.5); // Returns 5
function Say(string $message): void // As in PHP 7.2
{
echo $message;
}
Say('Hello, World!'); // Prints "Hello, World!"
function ArrayToStdClass(array $array): stdClass
{
return (object) $array;
}
$object = ArrayToStdClass(['name' => 'azjezz','age' => 100]); // returns an stdClass
function StdClassToArray(stdClass $object): array
{
return (array) $object;
}
$array = StdClassToArray($object); // Returns array
function ArrayToObject(array $array): object // As of PHP 7.2
{
return new ArrayObject($array);
}
function ObjectToArray(ArrayObject $object): array
{
return $object->getArrayCopy();
}
var_dump( ObjectToArray( ArrayToObject( [1 => 'a' ] ) ) ); // array(1 => 'a');
strict_types
이치노
힌트를 하지 않고 입력 합니다.strict_types
을 사용법
type 에는 " " " " 입니다.int $x
"라는뜻이었다.$x
int에 대해 강압적인 값을 가져야 합니다."강제할 수 있는 모든 값int
는 다음과 같은힌트를 합니다.
- 적절한 것
242
), - 뜨개질(
10.17
), - 부울(bool)
true
), null
, 또는- 선두 자릿수를 가진 문자열)
"13 Ghosts"
).
설정별strict_types=1
, 당신은 엔진에 말합니다.int $x
"$x는 int의 적절한 형식만 사용해야 하며 강제는 허용되지 않습니다."를 의미합니다.전환이나 잠재적 손실 없이 주어진 것만 정확하게 얻을 수 있다는 확신을 가지고 있습니다.
예:
<?php
function get_quantity(): int {
return '100 apples';
}
echo get_quantity() . PHP_EOL;
혼란스러운 결과를 초래할 수 있습니다.
Notice: A non well formed numeric value encountered in /Users/bishop/tmp/pmkr-994/junk.php on line 4
100
대부분의 개발자들은, 제 생각에,int
힌트는 "Only int"를 의미합니다.그게 아니라 "int 같은 것"을 의미합니다.strict_types를 이노블로 하면 예상되는 동작과 바람직한 동작을 얻을 수 있습니다.
<?php declare(strict_types=1);
function get_quantity(): int {
return '100 apples';
}
echo get_quantity() . PHP_EOL;
수율:
Fatal error: Uncaught TypeError: Return value of get_quantity() must be of the type int, string returned in example.php:4
유형 힌트를 사용하면 두 가지 교훈이 있습니다.
- 사용하다
strict_types=1
,항상. - 알림을 예외로 변환합니다. 예를 들어, 다음을 추가하는 것을 잊은 경우
strict_types
플러그마
언급URL : https://stackoverflow.com/questions/48723637/what-do-strict-types-do-in-php
'programing' 카테고리의 다른 글
와 Instant를 사용한 JPA 쿼리가 작동하지 않음 (0) | 2022.09.22 |
---|---|
코드 변경 후 magento 셋업 업그레이드를 실행할 때 Mysql 서버가 사라짐 (0) | 2022.09.22 |
전용 mariadb 서버에 적합한 구성 찾기 - 거대한 innodb 테이블에 적합 (0) | 2022.09.22 |
범위별 그룹화 및 임시 없는 상수 기준 (0) | 2022.09.22 |
양방향 암호화:검색할 수 있는 암호를 저장해야 합니다. (0) | 2022.09.22 |