Property Name from Array in OOP in PHP
Let's now look at how to access
an object's property by name
from an array element.
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');
?>
Suppose an array of properties is given:
<?php
$props = ['name', 'surn'];
?>
Now let's try to output the value of the property that is stored in the zero element of the array:
<?php
echo $user->$props[0]; // this will not work
?>
For such a complex property name to work, it must be enclosed in curly braces, like this:
<?php
echo $user->{$props[0]}; // will output 'john'
?>
The following class is given:
<?php
class Employee
{
public $name;
public $salary;
public $position;
public function __construct($name, $salary, $position)
{
$this->name = $name;
$this->salary = $salary;
$this->position = $position;
}
}
?>
An array is given:
<?php
$arr = ['name', 'salary', 'position'];
?>
Create an object of the Employee
class,
and then access its properties
through the array elements.