Názov metódy z premennej v OOP v PHP
Analogicky k názvom vlastností v premennej
je možné ukladať aj názvy metód. Pozrime sa
na príklad. Majme danú túto triedu User s gettermi vlastností:
<?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;
}
}
?>
Vytvorme objekt tejto triedy:
<?php
$user = new User('john', 'smit');
?>
Nech v premennej je uložený názov metódy:
<?php
$method = 'getName';
?>
Zavolajme metódu s názvom z premennej:
<?php
echo $user->$method(); // vypíše 'john'
?>
Daná je nasledujúca trieda:
<?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;
}
}
?>
Dané je pole:
<?php
$methods = [
'method1' => 'getName',
'method2' => 'getSalary',
'method3' => 'getPosition',
];
?>
Vytvorte objekt triedy Employee,
a potom pristúpte k jeho vlastnostiam
prostredníctvom prvkov poľa.