다음 코드의 실행 결과로 출력되는 내용은?

과목: PHP

문제 번호: 2998

medium
다음 코드의 실행 결과로 출력되는 내용은?
<?php
class Fruit {
    public $name;
    public $color;
    
    function __construct($name, $color) {
        $this->name = $name;
        $this->color = $color;
    }
    
    function __destruct() {
        echo "The fruit is {$this->name} and the color is {$this->color}.";
    }
}

$apple = new Fruit("Apple", "red");
?>
A. The fruit is Apple and the color is red.
B. Apple red
C. The fruit is and the color is .
D. 아무것도 출력되지 않음

정답: A



이 코드는 스크립트 종료 시 소멸자가 자동으로 호출되어 지정된 메시지를 출력합니다.

실행 과정:

1. new Fruit("Apple", "red") 호출로 생성자 실행

2. $this->name = "Apple", $this->color = "red" 설정

3. 스크립트 종료 시점에서 __destruct() 자동 호출

4. 중괄호 문법 {$this->name}{$this->color}로 변수 값이 문자열에 삽입됨

5. "The fruit is Apple and the color is red." 출력

소멸자는 생성자에서 설정된 객체의 속성값들에 정상적으로 접근할 수 있습니다.

💡 학습 팁

이 문제를 포함한 PHP 과목의 모든 문제를 순차적으로 풀어보세요. 진행상황이 자동으로 저장되어 언제든지 이어서 학습할 수 있습니다.