Method Name from Variable in OOP in PHP
Similarly to storing property names in variables,
you can also store method names. Let's
look at an example. Suppose we have the following
class User
with property getters:
<?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;
}
}
?>
Let's create an object of this class:
<?php
$user = new User('john', 'smit');
?>
Suppose a variable stores the method name:
<?php
$method = 'getName';
?>
Let's call the method with the name from the variable:
<?php
echo $user->$method(); // outputs 'john'
?>
Given the following class:
<?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;
}
}
?>
Given an array:
<?php
$methods = [
'method1' => 'getName',
'method2' => 'getSalary',
'method3' => 'getPosition',
];
?>
Create an object of the Employee
class,
and then access its properties
through the array elements.