从方法中的一类返回多个值 [英] Return multiple values from a method in a class
问题描述
我想从一个方法返回多个变量。
I am trying to return multiple variables from a method.
这是我到目前为止已经试过:
This is what I have tried so far:
这code是在类中的方法:
This code is the method in the class:
public function getUserInfo(){
$stmt = $this->dbh->prepare("SELECT user_id FROM oopforum_users WHERE username = ?");
$stmt->bindParam(1, $this->post_data['username']);
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$user_id = $row['user_id'];
$thumb = $row['thumbnail'];
}
return array($user_id, $thumb);
}
我试图将每个变量放置在列表在调用程序使用:
I attempt to place each variable in a list for use in the calling program:
session_start();
require_once('init.php');
$username = trim($_POST['username']);
// create a new object
$login = new Auth($_POST, $dbh);
if($login->validateLogin()){
$_SESSION['loggedin'] = true;
list($user_id, $thumb) = $login->getUserInfo($user_id, $thumb);
echo $user_id . ' ' . $thumb;
}
这已经行不通了。
我怎样才能返回多个变量数组从方法的类中在调用程序使用?
How can I return an array of multiple variables from a method within a class for use in the calling program?
推荐答案
您在类中定义的方法不匹配,你在呼唤什么。
The method that you define in the class doesn't match what you are calling.
// In the class, you have:
getUserInfo();
// But you call this:
getUserInfo($user_id, $thumb);
由于这个原因,PHP认为你调用一个不同的方法,因此没有返回值(至少没有用在这里)。
Because of this, PHP thinks you are calling a different method, and thus returns nothing (at least nothing of use here).
您调用应该是这样的:
list($user_id, $thumb) = $login->getUserInfo(); //Note that there are no parameters.
别的东西,你应该看看使用关联数组。它看起来是这样的:
Something else you should look at is using an associative array. It would look something like this:
//In the class:
public function getUserInfo() {
...
return array(
'id' => $user_id,
'thumb' => $thumb
);
}
//And then for your call:
$user = $login->getUserInfo();
echo $user['id'].' '.$user['thumb'];
编码时,这样的事情,因为我有$相关事物的数组p $ PFER,而不是一组独立的变量这将是我的preference。但是,这是所有preference。
This would be my preference when coding something like this, as I prefer having an array for related things, as opposed to a set of independent variables. But that is all preference.
这篇关于从方法中的一类返回多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!