생성자와 유효성 검사
Coddy의 Python 개발자를 위한 PHP 코스 레슨. 48개 중 30번째.
Python의 __init__은 self를 명시적으로 받지만, PHP의 __construct는 $this에 암시적으로 접근합니다. PHP의 생성자 프로퍼티 승격에 직접 대응하는 Python 구문은 없지만, dataclass를 사용하면 초기화 코드를 생성할 수 있습니다.
__construct는 new가 객체를 할당한 후 객체를 초기화합니다. 생성자 프로퍼티 승격을 사용하면 매개변수에 가시성 수정자를 지정하여 프로퍼티를 선언하고 초기화할 수 있습니다. 유효하지 않은 입력을 단순히 저장하기보다 불변 조건을 검증하세요. 하위 클래스에서 생성자를 선언하는 경우, 부모 클래스의 초기화가 필요하면 parent::__construct를 명시적으로 호출하세요.
Python 프로그램
class Tag:
def __init__(self, text):
self.text = text
print(Tag("draft").text)출력 결과:
draftPHP 프로그램
demo.php
<?php
declare(strict_types=1);
class Tag {public function __construct(public string $text){}} $t=new Tag("draft"); echo $t->text,"\n";
PHP 출력 결과:
draft챌린지
쉬움입력은 정수입니다. Capacity 생성자는 음수가 아닌 limit를 받고, 음수이면 InvalidArgumentException을 발생시켜 거부합니다. limit():int는 해당 값을 반환합니다. 드라이버는 생성이 거부되면 invalid를 출력합니다.
제공된 main 스크립트는 표준 입력에서 JSON 값 하나를 읽고, 지정된 공개 API를 확인한 뒤 결과를 출력합니다. 출력 없이 모듈 선언을 구현하세요. 실행 파일을 대체하거나 모듈에서 입력을 읽지 마세요. 입력은 명시된 유형과 범위를 충족합니다.
Capacity.php를 수정하세요. main.php는 잠긴 진입 파일입니다. 종속성은 상대 파일 이름과 함께 require_once __DIR__를 사용합니다.
직접 해보기
<?php
declare(strict_types=1);
require_once __DIR__."/Capacity.php";
function ensure(bool $ok,string $message):void{if(!$ok)throw new RuntimeException("API: ".$message);}
function capacityReport(int $n):string{try{return (string)(new Capacity($n))->limit();}catch(InvalidArgumentException $e){return "invalid";}}
$input=json_decode(trim(stream_get_contents(STDIN)),true,512,JSON_THROW_ON_ERROR);
ensure((new Capacity(3))->limit()===3,"constructor value");try{new Capacity(-2);throw new RuntimeException("accepted negative");}catch(InvalidArgumentException $e){}
echo capacityReport($input),"\n";
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
Python 개발자를 위한 PHP의 모든 레슨
직접 연습해 보세요: 온라인 PHP 컴파일러