생성자와 유효성 검사
Coddy의 C 개발자를 위한 PHP 코스 레슨. 48개 중 30번째.
C 팩토리 함수는 결과 구조체를 초기화하기 전에 인자를 검증할 수 있습니다. PHP __construct는 할당된 객체를 초기화하며 프로퍼티 프로모션(property promotion)은 값을 선언하고 저장할 수 있습니다. 프로모션이 비즈니스 규칙을 자동으로 검증하지는 않으므로, 객체를 사용하기 전에 유효하지 않은 상태를 거부하세요.
__construct는 new가 객체를 할당한 후 객체를 초기화합니다. 생성자 프로퍼티 프로모션(constructor property promotion)은 매개변수에 접근 제어자를 사용하여 프로퍼티를 선언함과 동시에 초기화할 수 있습니다. 유효하지 않은 입력을 단순히 저장하기보다 불변성을 검증하세요. 서브클래스가 생성자를 선언하는 경우, 부모 초기화가 필요할 때 parent::__construct를 명시적으로 호출하세요.
C 프로그램
#include <stdio.h>
struct Score{int points;};
static int score_new(int points,struct Score *out){if(points<0)return 0;out->points=points;return 1;}
int main(void) {
struct Score score; if(score_new(3,&score))printf("%d\n",score.points);
return 0;
}
소스 출력:
3PHP 프로그램
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를 출력합니다.
제공된 메인 스크립트는 표준 입력에서 하나의 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";
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
C 개발자를 위한 PHP의 모든 레슨
직접 연습해 보세요: 온라인 PHP 컴파일러