开发者

PHP if statements auto running

Probably a n00b question but take a look at the following code:

function admin_d开发者_如何学编程elete ( $id )
{

    if ($this->User->delete($id))
    {
        $this->Session->setFlash('The user with id: ' . $id . ' has been deleted!');
        $this->redirect(array('controller' => 'users', 'action' => 'admin_index'));
    }
}

Now as far as I'm concerned this would load the admin_delete view and then WHEN a user deletes the user it does the stuff inside the if statement. But it does the delete straight away??? Why? As it's just checking if the delete has taken place and their is nothing in the method to say actually delete it. So why does the code inside an if statement just automatically run like that if no conditionals return true or the function delete is being called outside of the if statement :/

Cheers


Well, let's take a look at how your if statement is constructed.

if ($this->User->delete($id))

You're saying basically, "If calling the function delete returns true, then run this other code". In order to see if it returns true, it's got to call the function. Essentially, since this isn't a compound boolean expression, your function call there will always be evaluated.


http://www.php.net/manual/en/language.expressions.php

Read the second last paragraph about expressions being converted to their boolean values when necessary. So even if the delete function does not explicitly return TRUE or FALSE, it may be returning a value that gets typecasted to a TRUE. Plus as suggested the delete function always gets called and evaluated as already suggested.

http://www.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜