PHP OOP에서 클래스 내부 메서드 호출
하나의 메서드 내부에서 다른 메서드를 $this를 통해 호출할 수 있습니다.
예제를 통해 살펴보겠습니다. 사용자 클래스와 해당 클래스의 속성을 반환하는 메서드가 있다고 가정해 보겠습니다:
<?php
class User {
public $name;
public function show() {
return $this->name;
}
}
?>
또한 문자열의 첫 글자를 대문자로 변환하는 cape 메서드가 있다고 가정해 보겠습니다:
<?php
class User {
public $name;
public function show() {
return $this->name;
}
public function cape($str) {
return mb_strtoupper(mb_substr($str, 0, 1)) . mb_substr($str, 1);
}
}
?>
이제 show 메서드 내부에서 cape 메서드를 활용해 보겠습니다:
<?php
class User {
public $name;
public function show() {
return $this->cape($this->name);
}
public function cape($str) {
return mb_strtoupper(mb_substr($str, 0, 1)) . mb_substr($str, 1);
}
}
?>
name 및 surn 속성을 가진 Student 클래스를 만드세요.
문자열의 첫 번째 문자를 가져와 대문자로 만드는 헬퍼 메서드를 작성하세요.
학생의 이니셜, 즉 이름과 성의 첫 글자를 반환하는 메서드를 만드세요.