Імя метаду з зменнай у ААП у PHP
Па аналогіі з назвамі ўласцівасцей у зменнай
таксама можна захоўваць і імёны метадаў. Давайце
паглядзім на прыкладзе. Хай у нас дадзены вось
такі клас 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
,
а затым звярніцеся да яго ўласцівасцей
праз элементы масіва.