문제

For most of my models in CakePHP I often create a function that handles saving a record. The default behavior for a Model's save is to return the data array or false.

I prefer the function to return true/false only. So I cast the result to (bool). Is this a valid way to cast something to boolean?

It's never not worked, but I've often wondered if it was a poor practice.

public function queue($url,$order=0)
{
    $result = $this->save(array(
        $this->alias => array(
            'agg_domain_id' => $domain_id,
            'order' => $order,
            'url' => $url
        )
    ));

    return (bool)$result;
}
도움이 되었습니까?

해결책 2

Is this a valid way to cast something to boolean?

Yes

It's fine to do that where you only want to know success or fail.

When it's not ok

The only potential problems with casting the return value like that, is if the return value could be a falsey type e.g.:

array()
0
""
" "

a call to save always returns a nested array or false - there is no scope for getting a false-negative result with a call to save.

다른 팁

From php.net:

To explicitly convert a value to boolean, use the (bool) or (boolean) casts. However, in most cases the cast is unncecessary, since a value will be automatically converted if an operator, function or control structure requires a boolean argument.

So if you do if($this->queue('url',0)) then the cast is not necessary.

But if you do if($this->queue('url',0) === true) then you need to cast. And casting with (bool) is absolute legitimate.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top