Function within function - PHP

Asked

Viewed 41 times

-2

I want to do a function that generates a string in alphanumeric format ( XXXXXX-XXXXXX ) and did the following function for such:

    private static function generateCode() {
    function generate() {
        $alphaNumeric = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; // ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
        $code = '';
        for ($i = 0; $i < 6; $i++) {
            $code .= $alphaNumeric[ rand(0,strlen($alphaNumeric) - 1) ];
        }
        return $code; // ex: X0XX0X
    }

    return sprintf("%s-%s",generate(),generate());

}

However I cannot use generate(), as I do to have this function inside the other?

  • I think it works well: https://ideone.com/7MRHUm

1 answer

2

It was supposed to be working, if you say the error that occurs maybe you can point out where it was, anyway do not really know why you did it, you could just create another private method and already solve and to call would use self::generate()

private static function generateCode()
{
    return sprintf("%s-%s", self::generate(), self::generate());
}

private static function generate()
{
    $alphaNumeric = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; // ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789

    $code = '';

    for ($i = 0; $i < 6; $i++) {
        $code .= $alphaNumeric[ rand(0,strlen($alphaNumeric) - 1) ];
    }

    return $code; // ex: X0XX0X
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.