Име методе из променљиве у ООП у 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,
а затим приступите његовим својствима
преко елемената низа.