I came across multiple ways of getting a setter done and I still haven't used them on big projects...
I want to know what is the difference between these two setters and which one of them is the best ?
public function setId($id){
if(is_int($id) && $id > 0){
$this->_id = $id;
return true;
}
return false;
}
Or
public function setId($id){
$id = (int) $id;
if($id > 0){
$this->_id = $id;
return true;
}
trigger_error("The id of your object could not be set/assigned !);
}
What is the use of the trigger_error() function and which of these setters is beneficial when there's code everywhere
Note: I'm using a hydrate() function to populate my object with data from a database !
If you are using PHP 7 you can use what is IMHO a much better version
public function setId( int $id ){
if($id > 0){
$this->_id = $id;
return true;
}
return false;
}
This will mean an error is thrown by PHP itself if the value isn't an int
The condition about checking if the value is greater than 0 is still needed and as long as this condition passes, then the function will return true
, I assume that a value less than 0 is an invalid value and this will return false
.
In your second example, the trigger_error()
is used to either log or raise an error which indicates that the method has been passed an invalid value, so somewhere this needs to be dealt with.
With the version of the code above, you could also type hint the return value...
public function setId( int $id ): boolean {
if($id > 0){
$this->_id = $id;
return true;
}
return false;
}
If you need to stick with your original options, then in my opinion, the first option is better, the second option does a cast to int and then checks if the result is an int, so this is not useful.