开发者

PHP: return array?

I have index.php, and function.php.

In index.php i have included function.php

In i开发者_运维问答ndex.php im calling login("Bla","123"); which exists in function.php

In index.php I have a if (!empty($err)){ foreach(..) echo $err ... }

login() should return a array called $err, (with return $err; ) if there is any errors, and then it should echo it out in the foreach in index.php..

But somehow I can not get it to work. Can't you do it like this? Im not getting anything back.

I have in the login() :

$err = array();
    $err[] = "Something went wrong";
        return $err;
        exit();

What's wrong here? Or any other solution to do this?


return return returns the value of $err. It does not make the variable $err globally available.

Try using:

$err = login('Bla', '123');


replace the exit() with just return;

function login()
{
    //Blah
    exit();
}
login();

echo 'You shall never see this.';

this is what you should be doing:

$errors = array();
function login($user,$pass)
{
    global $errors;
    if(empty($user) || empty($pass))
    {
        $errors[] = "username / Password invalid";
    }

    //More Checks

    //at the end.
    if(count($errors) == 0) /*no errors*/
    {
        return true;
    }
}

and then in your index.php

if(!login("user","pass"))
{
    foreach($errors as $error)
    {
        echo $error . "<br />";
    }
    exit();
}

//Successful login


I recommend reading up on variable scope: http://www.php.net/manual/en/language.variables.scope.php

Based on what you've said you're attempting to return a variable from one scope and use it in another scope using the same name, but without setting it explicitly.

function login() {
    $var = 123;
    return $var;
}

login(); // $var won't exist.
$abc = login(); // To login() it is called $var
// but here $abc has the same value as $var inside of login() because it was returned.
// not because it has the same name.


ive already added one answer but i think ill add another describing OOP way to do this.

Create a file called login.class.php and create a class like so

class Login
{
    var $username,$password;

    public function __cosntruct($username,$password)
    {
        $this->username = $username;
        $this->password = $password;
    }

    //Checks
    public function isValidUsername()
    {
       return strlen($this->username) > 8;
    }

    //..Etc
}

then you can do:

$Login = new Login("Username","Password");

if(!$Login->isValidUsername())
{
    echo 'username invalid';
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜