我正在学习php,遇到了以下麻烦:
我有2个对象,比如
class Fruit {
public $weight;
}
$apple = new Fruit();
$apple->weight = 1;
$banana = new Fruit();
$banana->weight = 2;
后来,我从用户那里得到了一些输入作为变量(例如,您最喜欢哪种水果?):
$user_preference = 'apple';
现在,如何动态引用正确的对象?如何获得类似的东西
echo $user_preference->weight;
?
答案 0 :(得分:4)
我会创建一个地图(例如,当从数据库中检索数据时,它会有用)
$apple = new Fruit();
$apple->weight = 1;
$banana = new Fruit();
$banana->weight = 2;
$fruitMap = ['apple'=>$apple,'banana'=>$banana];
$user_preference = 'apple';
echo $fruitMap[$user_preference]->weight;
但是请检查密钥是否存在
答案 1 :(得分:2)
您可以使用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
请注意,这可能会导致安全漏洞,因为
假设您进行了echo $$user_input;
并且用户输入是database_password
为避免这种情况,您需要清理用户输入,例如:
<?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";
}
但这是以输入更多代码为代价的。 ka_lin's solution更安全,更易于维护