Property Name from Another Object in OOP in PHP
A property name can even be a property of another
object. 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');
?>
Let's also say we have a class
Prop
, which will store the name of
a property in its value
property:
<?php
class Prop
{
public $value;
public function __construct($value)
{
$this->value = $value;
}
}
?>
Let's create an object of this class:
<?php
$prop = new Prop('name');
?>
Now, using this object, let's output the user's name:
<?php
echo $user->{$prop->value}; // outputs 'john'
?>
Given the following class:
<?php
class Employee
{
public $name;
public $salary;
public $position;
public function __construct($name, $salary, $position)
{
$this->name = $name;
$this->salary = $salary;
$this->position = $position;
}
}
?>
Also given this class:
<?php
class Data
{
public $prop1 = 'name';
public $prop2 = 'salary';
public $prop3 = 'position';
}
?>
Output the properties of the Employee
object
through the Data
object.