用PHP表示多行的简写

时间:2014-02-18 15:36:28

标签: php

我似乎无法找出PHP的确切控制结构if / else。

目前我有这个功能,但有人能告诉我PHP是否只是在寻找“标签”?是否可以在1个语句中触发多个函数?就像现在它只是重定向到一条路线,但是我想要在重定向之前更新用户时给我发送电子邮件。这还可以用速记吗?

public function store()
{
    return ($user = $this->user->store(Input->all())) ?

        Redirect::route('user.index')
            ->with('flash_message', 'User succesfully created!', ['user' => $user]) :

        Redirect::route('user.create')
            ->withInput()
            ->withErrors($this->user->getErrors());
}

2 个答案:

答案 0 :(得分:1)

这是php if / else的文档:

http://www.php.net/manual/en/control-structures.elseif.php

? :结构是if / else的简写,但将它用于复杂的事情并不是一个好习惯。它使您的代码不可读。 http://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary

否则php不关心空格。

答案 1 :(得分:0)

使用if / else,它看起来像这样:

public function store()
{
    if ($user = $this->user->store(Input->all()))
    {
        return Redirect::route('user.index')
            ->with('flash_message', 'User succesfully created!', ['user' => $user]);
    }
    else
    {
        return Redirect::route('user.create')
            ->withInput()
            ->withErrors($this->user->getErrors());
    }
}

如果if没有完成作业,那么读起来会更容易。例如:

public function store()
{
    $user = $this->user->store(Input->all())

    if ($user)
    {
        return Redirect::route('user.index')
            ->with('flash_message', 'User succesfully created!', ['user' => $user]);
    }
    else
    {
        return Redirect::route('user.create')
            ->withInput()
            ->withErrors($this->user->getErrors());
    }
}
相关问题