Accessing Property by Variable Name in OOP in PHP
You can access object properties
by a variable name. Let's see
how this can be done. Suppose we have the following
class User
:
<?php
class User
{
public $name;
public $surn;
public function __construct($name, $surn)
{
$this->name = $name;
$this->surn = $surn;
}
}
?>
Let's create an object of this class:
<?php
$user = new User('john', 'smit');
?>
Let's output the value of its property:
<?php
echo $user->name; // outputs 'john'
?>
Suppose we have a variable that stores the property name:
<?php
$prop = 'name';
?>
Now let's use the variable value as the property name:
<?php
$prop = 'name';
echo $user->$prop; // outputs 'john'
?>
Given the following class:
<?php
class Employee
{
public $name;
public $salary;
public function __construct($name, $salary)
{
$this->name = $name;
$this->salary = $salary;
}
}
?>
Given the following variables:
<?php
$prop1 = 'name';
$prop2 = 'salary';
?>
Create an object of the Employee
class,
and then access its properties
through the given variables.