反对在 if 子句中返回布尔值

发布于 2024-09-24 21:33:34 字数 255 浏览 2 评论 0原文

我对各种变量何时以及如何返回还不够了解。考虑到我有一个条件语句,其中有一个对象要在其中进行验证。我说得对吗,这是作为布尔值返回的。

if($id = $oE->validate($_POST, $_FILES)){
...
}

我真正想要的是如果有任何错误,它会返回一个错误数组,否则它将返回更新内容的 $id 。

有了上面的内容,如果 validate() 对象返回任何值,它似乎会返回布尔 true ?

I don't know enough about when and how various variables are returned. Considering I have an conditional statement with an object to validate inside of this. Am I right that this is returned as a boolean value.

if($id = $oE->validate($_POST, $_FILES)){
...
}

What I really want is for this to return an array of errors if there are any errors, otherwise it will return the $id of the updated content.

With this above, it seems to return a boolean true if any value at all is returned by the validate() object??

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

饮湿 2024-10-01 21:33:34

PHP 将任何非零值解释为 true。您需要的是传递一个包含任何错误代码的引用,并让函数在失败时返回 false 或在成功时返回 id。 IE:

class Validator()
    {
    function validate($post,$files,$errorRef)
        {
        //Your code here
        if ($success)
            {
            return $id;
            }
        else
            {
            $errorRef = $errorCode;
            return false;
            }
        }
    }
//
$oE = new Validator;
$error = NULL;
$id = $oE->validate($_POST,$_FILES,&$error);
if ($id !== false) //If validator did not return false
    {
    //Stuff happens
    }
else
    {
    switch ($error)
        {
        //Error Handling Stuff
        }
    }

PHP interprets any non-zero value as true. What you need is to pass a reference which holds any error codes, and get the function to either return false on failure or the id on success. ie:

class Validator()
    {
    function validate($post,$files,$errorRef)
        {
        //Your code here
        if ($success)
            {
            return $id;
            }
        else
            {
            $errorRef = $errorCode;
            return false;
            }
        }
    }
//
$oE = new Validator;
$error = NULL;
$id = $oE->validate($_POST,$_FILES,&$error);
if ($id !== false) //If validator did not return false
    {
    //Stuff happens
    }
else
    {
    switch ($error)
        {
        //Error Handling Stuff
        }
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文