다음 코드의 실행 결과는?
다음 코드의 실행 결과는?
<?php
class Fruit {
public $name;
private $weight;
public function __construct($name, $weight) {
$this->name = $name;
$this->weight = $weight;
}
public function getInfo() {
return "Name: {$this->name}, Weight: {$this->weight}";
}
private function getWeight() {
return $this->weight;
}
}
$apple = new Fruit('Apple', '200g');
echo $apple->getInfo();
echo $apple->getWeight(); // 이 라인의 결과는?
?>
정답: B
이 코드는 부분적으로 실행된 후 오류가 발생합니다.
단계별 실행 분석:
1. 객체 생성 및 초기화
⦁
new Fruit('Apple', '200g')
호출로 생성자 실행⦁
public
생성자이므로 정상 실행⦁
$this->name = 'Apple'
, $this->weight = '200g'
설정2. 첫 번째 출력:
$apple->getInfo()
⦁
getInfo()
메서드는 public
이므로 외부에서 호출 가능⦁ 메서드 내부에서
private
속성 $this->weight
접근 가능 (같은 클래스 내부)⦁ "Name: Apple, Weight: 200g" 정상 출력
3. 두 번째 출력:
$apple->getWeight()
⦁
getWeight()
메서드는 private
이므로 클래스 외부에서 호출 불가⦁ Fatal Error 발생: "Call to private method"
핵심 포인트:
⦁
private
속성은 같은 클래스의 public
메서드에서 접근 가능⦁
private
메서드는 클래스 외부에서 절대 호출 불가
💡 학습 팁
이 문제를 포함한 PHP 과목의 모든 문제를 순차적으로 풀어보세요. 진행상황이 자동으로 저장되어 언제든지 이어서 학습할 수 있습니다.