PHPにおけるOOPでの変数からのメソッド名の指定
プロパティ名を変数に格納できるのと同様に、
メソッド名も変数に格納することができます。
例を見てみましょう。以下に示すような
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 クラスのオブジェクトを作成し、
配列の要素を通じてそのプロパティにアクセスしてください。