我如何使用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

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.