⊗ppOpCgPNAs 39 of 107 menu

Property Name from Associative Array in OOP in PHP

Let's now see how to access an object's property by name from an element of an associative array. 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 = ['prop1' => 'name', 'prop2' => 'surn']; ?>

Let's access the object's property, the name of which is stored in the element of our array:

<?php echo $user->{$props['prop1']}; // 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 = [ 'prop1' => 'name', 'prop2' => 'salary', 'prop3' => 'position' ]; ?>

Create an object of the Employee class, and then access its properties through the array elements.

byenru