问题:printf正在运行,但我没有从对象中获取名称。一旦mySQL数据库的结果使用foreach循环返回,我想生成一个类的实例。我想我需要使用变量变量。我更喜欢
的语法${'class' . $var} // only ever heard of $$var syntax but saw this on SO
我得到了什么......
include_once 'includes/dbh.inc.php';
include 'class/User.php'; // class has two fields... name and email with
// getter = getName
if(!$conn){
die("connection failed: " . mysqli_connect_error());
} // connection is successful
$sql = "SELECT user_name As Name, user_email As Email FROM users;";
$result = mysqli_query($conn, $sql);
$rows = array();
if (mysqli_num_rows($result) > 0) {
$i= 1;
while($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
printf ("Name: %s\n Email: %s\n\n", $row["Name"], $row["Email"]);
${'user' . $i} = new User();
${'user' . $i}->setName($row['Name']);
echo $pattern1->name();
$i++;
}
我是在正确的道路上吗?请帮帮我。一如既往,我是一名学习初学者,我喜欢听取建议以扩大我的理解。提前谢谢。
答案 0 :(得分:1)
每当你有$var1
,$var2
之类的变量时,你应该使用数组。做一些像
$rows = array();
while($row = mysqli_fetch_assoc($result)) {
printf ("Name: %s\n Email: %s\n\n", $row["Name"], $row["Email"]);
$newUser = new User();
$newUser->setName($row['Name']);
$newUser->setEMail($row['Email']);
$rows[] = $newUser;
}
这将以更干净的方式创建带有User对象列表的$rows
数组。
您可以使用
循环访问它foreach ( $users as $user) {
echo $user->getName();
}