This code will output the same. My question is, what is the correct way to do this. The first approach or the second? Or there is any better way? I don’t see any advantage of one Class over the other.
<?php
class Client{
var $id;
var $email;
function __construct($id){
$this->id=$id;
}
public function get_email($db){
$sql = $db -> prepare(" SELECT email FROM users WHERE id = ? ");
$sql -> bind_param('i', $this->id);
$sql->execute();
$sql->bind_result($email);
if ($sql -> fetch()) {
return $this->email=$email;
}
else
return false;
}
}
class Client_{
public function get_email($db, $id){
$sql = $db -> prepare(" SELECT email FROM users WHERE id = ?");
$sql -> bind_param('i', $id);
$sql->execute();
$sql->bind_result($email);
if ($sql -> fetch()) {
return $email;
}
else
return false;
}
}
?>
index.php
<?php
$Client = new Client(1);
$a = $Client -> get_email($db);
print_r($a);
$Client_ = new Client_();
$b = $Client_ -> get_email($db, 1);
print_r($b);
?>
In second approach it does not make sense to instantiate class, as there is nothing to be stored for future use. So it would be better to use “static class” if varying data is stored somewhere else:
If i shoul make decision between those two I’m going to take first one.
I dont know how you are going to use either one of those classes but still for me it makes more sense to store
$dband supply$idfrom outside and make$emaillocal:Also changed this line:
return $this->email=$email;, maybe I got it wrong but I think that it just doesn’t make sense.