dongsisui7562 2010-11-25 20:32
浏览 31
已采纳

将变量名称作为字符串传递

I'm trying to perform the same function dosomething() to multiple variables $lastsum $avatar $angels $city $square in PHP.

$lastsum->dosomething();
$avatar->dosomething();
$angels->dosomething();
$city->dosomething();
$square->dosomething();

Is there a way to make this code cleaner by listing the names of the variables in a string array and perform the function with a for loop. I'm looking for something like this. Does anyone know the right way to do this in PHP?

$all = ['lastsum' , 'avatar', 'angels' , 'city' , 'square'];
foreach (....){
    $(nameofvariable)->dosomething();
}
  • 写回答

4条回答 默认 最新

  • douju1928 2010-11-25 20:53
    关注

    What's wrong with

    $all = array($lastsum , $avatar, $angels, $city, $square);
    foreach (....){
        $variable->dosomething();
    }
    

    To achieve exactly what you're looking for, use variable variables

    $all = array('lastsum' , 'avatar', 'angels' , 'city' , 'square');
    foreach ($all as $x) {
        $$x->dosomething();
    }
    

    Many people consider this to be bad style though.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改
  • ¥15 Windows 系统cmd后提示“加载用户设置时遇到错误”
  • ¥50 vue router 动态路由问题
  • ¥15 关于#.net#的问题:End Function
  • ¥15 无法import pycausal
  • ¥15 VS2022创建MVC framework提示:预安装的程序包具有对缺少的注册表值的引用
  • ¥15 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义
  • ¥15 嵌入式--定时器使用
  • ¥20 51单片机学习中的问题