2 回答

TA贡献1789条经验 获得超10个赞
我会创建一个地图(例如,当从数据库中检索数据时很有用)
$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;
但是检查密钥是否存在

TA贡献1846条经验 获得超7个赞
您可以使用变量变量:
<?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 的解决方案更安全,更易于维护
- 2 回答
- 0 关注
- 124 浏览
添加回答
举报