Име на метод от променлива в ООП в 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,
след което се обърнете към неговите свойства
чрез елементите на масива.