⊗ppOpCgPNF 40 of 107 menu

Property Name from Function in OOP in PHP

The property name of an object can also be taken from a function. Let's see how it's done. Let's say 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 we have the following function:

<?php function getProp() { return 'name'; } ?>

Let's access the object's property, the name of which is returned by our function:

<?php echo $user->{getProp()}; // 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; } } ?>

The following functions are given:

<?php function getProp1() { return 'name'; } function getProp2() { return 'salary'; } ?>

Create an object of the Employee class, and then access its properties through the results of executing the functions.

byenru