PHP OOP에서 변수에 저장된 메서드 이름 사용하기
속성 이름을 변수에 저장하는 것과 유사하게
메서드 이름도 변수에 저장할 수 있습니다.
예제를 통해 살펴보겠습니다. 다음은 속성에 대한
getter 메서드를 가진 User 클래스입니다:
<?php
class User
{
private $name;
private $surn;
public function __construct($name, $surn)
{
$this->name = $name;
$this->surn = $surn;
}
public function getName()
{
return $this->name;
}
public function getSurn()
{
return $this->surn;
}
}
?>
이 클래스의 객체를 생성해 보겠습니다:
<?php
$user = new User('john', 'smit');
?>
변수에 메서드 이름을 저장해 보겠습니다:
<?php
$method = 'getName';
?>
변수에 저장된 이름으로 메서드를 호출해 보겠습니다:
<?php
echo $user->$method(); // 'john'을 출력합니다
?>
다음 클래스가 주어졌습니다:
<?php
class Employee
{
private $name;
private $salary;
private $position;
public function __construct($name, $salary, $position)
{
$this->name = $name;
$this->salary = $salary;
$this->position = $position;
}
public function getName()
{
return $this->name;
}
public function getSalary()
{
return $this->salary;
}
public function getPosition()
{
return $this->position;
}
}
?>
다음 배열이 주어졌습니다:
<?php
$methods = [
'method1' => 'getName',
'method2' => 'getSalary',
'method3' => 'getPosition',
];
?>
Employee 클래스의 객체를 생성한 후,
배열 요소를 통해 해당 속성에 접근해 보세요.