ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Type Declaration
    서버/PHP 2020. 11. 5. 08:35

    출처:youtu.be/0MYqGSplVQs

    유저들이 메서드에 해당하는(적절한) 데이터를 전송하는지 확실하게 해준다.

     

    사용하는 타입형

     

    Methods

    By using type declaration, we can throw an error if wrong type is given!

    Works with:

    -class/interface names

    -self(used to reference to same class)

    -array

    -callable

    -bool

    -float

    -int

    -string

    -iterable

    -object

     

    public function setName(string $newName){
    $this->name=$newName;
    }

    c#등등에서는 당연히 쓰는 것 

    (string $newName)

     

    타입에 맞지 않아도 에러를 발생하지 않는 경우가 있다

    예) string  에 int 1 을 입력해도 '1' 로 인정되는 경우

     

    이를 방지해 strictmode 가 있다.

    <?php
    declare(strict_types=1);
    ?>

    1은 true 0은 false

     

    string 은 string만 int 는 int 만 

     

    에러캐치는 

     

    <?php
    
    $person1 = new Person();
    
    
    
    try{
    
    $person1->setName(2);
    
    echo $person1->getName();
    
    }catch(TypeError $e){
    
    echo "Error!: ".$e->getMessage();
    
    }
    
    ?>

    이런 식으로 try catch 문에서 TypeError 

     

     

    '서버 > PHP' 카테고리의 다른 글

    PDO::  (0) 2020.11.06
    [객체지향PHP]8.Interface  (0) 2020.11.06
    [객체지향PHP]7.Namespace  (0) 2020.11.05
    [객체지향PHP]6.include  (0) 2020.11.05
    [객체지향PHP]5.Static ::(Scope Resolution Operator)  (0) 2020.11.05
Designed by Tistory.