You can use Variable variables :
<?php
class Fruit {
public $weight;
}
$apple = new Fruit();
$apple->weight = 1;
$banana = new Fruit();
$banana->weight = 2;
$user_preference = 'apple';
// vv---------------- Check this notation
echo $$user_preference->weight; // outputs 1
Test it yourself
Note that this can lead to security breaches because
- Never trust user inputs.
- Never trust user inputs especially when it comes to control your code execution.
- Never trust user inputs.
Imagine you do echo $$user_input; and user input is database_password
To avoid it, you need to sanitize user inputs, in example :
<?php
class Fruit {
public $weight;
}
$apple = new Fruit();
$apple->weight = 1;
$banana = new Fruit();
$banana->weight = 2;
$allowed_inputs = ['apple', 'banana'];
$user_preference = 'apple';
if (in_array($user_preference, $allowed_inputs))
{
echo $$user_preference->weight; // outputs 1
}
else
{
echo "Nope ! You can't do that";
}
But this is at the cost of typing more code. ka_lin's solution is safer and easier to maintain
echo ${$user_preference}->weight;orecho $$user_preference->weight;. See variable variables. It's not exactly a recommended feature to use in most cases though.