duanbairan4235 2019-07-25 14:31
浏览 23
已采纳

我如何使用PHP中的动态变量

I wasn't able to output the value of $id,

My first code was:

class add_User
{
    public function User($id) { //<-- in //
        $statement = "INSERT INTO `users` " . $this->$id. "varchar(255)"; // just nothing
        print($statement); //<-- out //
    }

    public function Moderator($id) {
        $statement = "INSERT INTO `users` " . $this->$id . "varchar(255)"; // just nothing
        print($statement);
    }
}

$check_statement = new add_User();

$check_statement->User('user1');

$check_statement->Moderator('mod1');

My current code works fine with just $this->$id, $id

  • 写回答

1条回答 默认 最新

  • dongyangben6144 2019-07-25 14:40
    关注

    You have a few issues here:

    • $this->$id would be a variable class variable. If the ID you're passing into the function was 'abc', then it would be looking for the class variable/property $this->abc
    • $this implies it's a class variable. You don't have any class variables defined, so this is not what you want, either.

    You're passing a variable into the function, so you want to use that. All you need to do is drop $this, and you'll get what you're looking for.

    class add_User
    {
        public function User($id) { //<-- in //
            $statement = "INSERT INTO `users` " . $id. "varchar(255)"; // just nothing
            print($statement); //<-- out //
        }
    
        public function Moderator($id) {
            $statement = "INSERT INTO `users` " . $id . "varchar(255)"; // just nothing
            print($statement);
        }
    }
    

    This will fix your printing. For the next step, as I mentioned in my comment, this would not be valid sql. varchar(255) would be for the creation of a column, not the insertion of data. So you'll still have to do some tweaking to get the query right once you get to that part.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥15 统计大规模图中的完全子图问题
  • ¥15 使用LM2596制作降压电路,一个能运行,一个不能
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式