我是PHP OOP的新手,所以我不确定我是否会以正确的方式解决这个问题。父方法isRegistered()将正确地查询db并在从父级调用方法时返回一个值($ affected_rows),但是当我从中调用方法时,它只会“回显”该值(不会返回它)孩子,所以我不确定我是否错误地构建了孩子。这是我的代码:
//Log in with social credentials
if(isset($_POST["fb-reg"])) {
$fbOptions = array(
'email' => "joe@gmail.com",
'fbId' => "678910",
'handler' => $handler); //the db connection
fbRegister($fbOptions);
}
//Instantiate parent and child and get results of query
function fbRegister($fbOptions) {
$a = new newUser();
$fb = new fbUser($fbOptions);
$fb->isRegistered(); // will echo back $affected_rows
$y = isRegistered();
echo $y; // does not return value of $affected_rows
}
//Parent class
class newUser {
public $email;
public $pass;
public $dbconn;
public $confirm;
public $message;
public function __construct($options) {
$this->email = $options['email'];
$this->pass = $options['password'];
$this->confirm = $options['confirm'];
$this->dbconn = $options['handler'];
$this->message = array();
}
// CHECK IF USER EXISTS ====================================
public function isRegistered() {
$sql=("SELECT * FROM Test WHERE Email = :email");
$query = $this->dbconn->prepare($sql);
$query->execute(array(':email' => $this->email));
$affected_rows = $query->rowCount();
return $affected_rows; // query works but does not return value to calling function
echo $affected_rows; // query result will be echoed by calling function
}
}
//Child class
class fbUser extends newUser{
public $id;
public $email;
public $dbconn;
function __construct($fbOptions) {
$this->id = $fbOptions['fbId'];
$this->email = $fbOptions['email'];
$this->dbconn = $fbOptions['handler'];
}
public function isRegistered() {
parent::isRegistered($this->email, $this->dbconn);
}
}
答案 0 :(得分:4)
我需要在子方法中返回:
return parent :: isRegistered($ this-> email,$ this-> dbconn);