On Fri, Apr 13, 2012 at 16:22, Pal Konyves <paul.kony...@gmail.com> wrote:
> Well, if you want to use empty in the above mentioned situations, you might
> need the change. I personally don't like using empty(). I use it only on
> arrays, that's because semantically fits: array is empty.
>
> In other situations I prefer comparing against the according return type
> because it improves code readability. Dynamic typing in PHP one of the
> reasons of messy code anyways.
>
> I'm gonna try to give you alternatives of design for your examples below:
>
>> Browsing around Google it seems that one of the most common source of
>> the function call in write context error is people trying to do
>> if(empty(trim($xyz)). You don't necessarily need the result of
>> trim($xyz), so it's reasonable not to save it into a temporary
>> variable.
>
> if( trim($xyz) === ""); // as I talked about semantics and types above
>
>>
>> Another example for example would be a function like this:
>>
>> public function isValid() {
>>    if (...) { $this->addError('xyz'); }
>>    if (...) { $this->addError('abc'); }
>>    if (...) { $this->addError('foo'); }
>>    if (...) { $this->addError('bar'); }
>>
>>    return empty($this->getErrors());
>
> return $this->getErrorsCount();
>
>> }
>>
>> Furthermore you don't necessarily have to throw the return value away.
>> For example I commonly write code like this:
>>
>> if (null === $result = $this->foo()) {
>>    throw new Exception(...);
>> }
>> $result->doSomething();
>
> I used to use this kind of formula, but I realised It neither improves
> performance nor readability, especially if you want to use $result after
> the if statement.
>
>>
>> You can do something similar with empty():
>>
>> if (empty($values = $this->getValues()) {
>>    return;
>> }
>> $this->doSomethingWith($values);
>
> I haven't try this but I assume this code is valid by precedence order. I
> might be wrong, but still my above argument exist.
>
>>
>> I know, not everyone likes that kind of coding style, but I think it
>> has it's uses.
>
>
> Etienne Kneuss:
> " People typically assume empty checks for the empty
> string here, and it doesn't." -- why not?

What I meant is that when people do:

$str = trim($foo);

if (empty($str)) {

}

they typically want to check if the string is empty, i.e. contains 0
characters. They usually forget that empty() will also return true on
the string "0".

>
>
> Pal



-- 
Etienne Kneuss
http://www.colder.ch

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to