Reputation: 18103
Ok, i got a error class, where you can do $error->add($message);
which will store the $message to an array inside the class.
private $_errorArray = array();
public function add($message){
$this->_errorArray[] = $message;
}
public function output(){
return $this->_errorArray;
}
public function exists(){
if(empty($this->_errorArray)){
return false;
}else{
return true;
}
}
}
Now what if i have a class AlbumMapper, that grabs and assigns variables. But if it cant grab (no rows to select), then it should add a message to this error.
class AlbumMapper {
private $_pdo;
function __construct($pdo){
$this->_pdo = $pdo;
}
public function fetch($album){
$columns = "id, title, uID, date";
$table = TABLE_USERS_ALBUMS;
$query = "SELECT ".$columns." FROM ".$table." WHERE id=:id";
$query = $this->_pdo->prepare($query);
$query->bindValue(":id", $album->id());
$query->execute();
if( ! $data = $query->fetch() ) { $errors->add("Album not exists"); }
$album->assign($data);
}
}
And, i would like to output the error OUTSIDE the class. So:
$error = new errors();
$albumMapper->fetch($album);
if ( $error->exists() ) { $error->output(); }
I can make this work, if i pass the $error to the fetch() method, but then i would need to pass the $error to all my methods, and it dont feel the best way to do it.
I can also do this by creating the object inside the object $albumMapper, so in the constructor it does: $error = new errors();
and then you can add the errors to this, but how would i output the errors then, if any?
Upvotes: 0
Views: 62
Reputation: 54739
You just need to globalize the error class so the function can use it. Inside your fetch function, on the first line, just define $error
as global, like so:
public function fetch($album){
global $error;
$columns = "id, title, uID, date";
Although $error
is not the greatest variable name to globalize somewhere. Also your $errors->add()
line inside the function would need to be changed to $error->add()
. This should work but I don't strongly recommend doing this.
Upvotes: 1
Reputation: 57728
Perhaps this is a stupid suggestion, but why aren't you using Exceptions
?
The beautiful thing about Exceptions
is that they bypass normal code flow so you don't have to worry about return values and such.
Upvotes: 1