I have written a validation
trait for my model classes, as well as an error reporting library which formats and returns a JSON object of errors, warnings, etc.
In my validation
trait, I have this method...
function hasValue($value)
{
return (isset($value) && !(trim($value) === ''));
}
PHP will throw a warming if I just try to use !(trim($value)
in a conditional that tells me the variable is undefined. So, you have to do this...
if (isset($value) && !(trim($value) === ''))
//Do Something
I created this method to consolidate a very common task requiring two methods into a single method, but I am getting the same warning as if I had used the trim()
method alone.
Is there a way to do this without turning off warnings?
EDIT
There seems to be some confusion. I need this to work for variables, and object properties. I'm attempting to turn this...
if (empty($obj->email) && $this->validateEmail($obj->email))
//Do Something
Into this...
if ($this->validateEmail($obj->email))
//Do Something
By having my hasValue()
method to call on will, and inside the validateEmail()
method.
The problem you're having is that your function
hasValue()
evaluates both statementsisset($value)
and!(trim($value) === '')
as oneInstead you should evaluate
!(trim($value) === '')
ifisset($value)
equals true. This is done by removing the outer parenthesis.That would resolve the warning, however
hasValue()
sounds more like a function to check if any variable has a value, perhaps do this instead:For a longer list of values what isset and empty does see here