How do I alert an error if it occurs in an object's constructor?
Example:
Say im creating an object that relies on a give record from the database
zipcodes.
In php...
<?php
class Zip {
private $zipcode;
function __construct(zipcode) {
//..code the looks up zipcode
$numOfRecords = $mysqli->affected_rows;
if ($numOfRecords == 0) {
//this takes advantage of dynamically typed languages and passes a
boolean
//value instead of the newly created object to the variables thats
being
//assigned
return false;
} else {
$this->zipcode = zipcode;
}
}
}
//then...
if ($o = new Zip('90210')) {
//code if zipcode exists
} else {
//code if it doesn't
}
?>
In ruby..
class Zip
def initialize(zipcode)
o = Zipcode.find_by_zipcode(zipcode)
if o.length == 0
return false
else
@zipcode = zipcode
end
end
end
//then...
if o = Zip.new('00000')
//this block execute whether or not that zip code exists
else
//never happens
end
..now i know there are easier ways to do this, but its just an example
to illustrate my point.
···
--
Posted via http://www.ruby-forum.com/.