猿问

如何通过 PHP 中的另一个变量引用对象?

我正在学习 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; 

?


江户川乱折腾
浏览 125回答 2
2回答

至尊宝的传说

我会创建一个地图(例如,当从数据库中检索数据时很有用)$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;但是检查密钥是否存在

喵喵时光机

您可以使用变量变量:<?phpclass Fruit {&nbsp; &nbsp; public $weight;}$apple = new Fruit();$apple->weight = 1;$banana = new Fruit();$banana->weight = 2;$user_preference =&nbsp; 'apple';//&nbsp; &nbsp;vv---------------- Check this notationecho $$user_preference->weight;&nbsp; // outputs 1自己测试一下请注意,这可能会导致安全漏洞,因为永远不要相信用户输入。永远不要相信用户输入,尤其是在控制代码执行时。永远不要相信用户输入。想象一下echo $$user_input;,用户输入是database_password为避免这种情况,您需要清理用户输入,例如:<?phpclass Fruit {&nbsp; &nbsp; public $weight;}$apple = new Fruit();$apple->weight = 1;$banana = new Fruit();$banana->weight = 2;$allowed_inputs = ['apple', 'banana'];$user_preference =&nbsp; 'apple';if (in_array($user_preference, $allowed_inputs)){&nbsp; &nbsp; echo $$user_preference->weight;&nbsp; // outputs 1}else{&nbsp; &nbsp; echo "Nope ! You can't do that";}但这是以输入更多代码为代价的。ka_lin 的解决方案更安全,更易于维护
随时随地看视频慕课网APP
我要回答