Jump to content
iwato

A Problem of Scope

Recommended Posts

function select_color_pair($lum_differential, $base = true, $type = true) {
  function random_color($base, %type){
    ... Do something with $base and $true
  }
}

QUESTION:  Is the second appearance of the parameters $base and $type necessary?

Roddy

Share this post


Link to post
Share on other sites

That's a pretty vague question.  And why are you trying to define a function within another function?

Share this post


Link to post
Share on other sites

DILEMMA:  What I would like following function to do is keep iterating until it has satisfied the condition:

abs($random_lum - $contrast_lum) > $lum_differential

What it does instead is return NULL and stops, when it is unable.

function select_color_pair($base, $lum_differential =0.25){
    $color_pair = array();
    $result = array( 'rgb' => [], 'hex' => '' );
    for( $i=0; $i<3; $i++ ){
        $rand = mt_rand(0, 255);
        $result['rgb'][] = $rand;
        $dechex = dechex($rand);
        if(strlen($dechex) < 2){
            $dechex = '0' . $dechex;
        }
        $result['hex'] .= $dechex;
    }
    if ($base == true) {
        $random_lum = COLOR::fromRGB($result['rgb'])->getLuminance();
        $contrast_color = COLOR::fromRGB($result['rgb'])->invert();
        $contrast_lum = COLOR::fromHex($contrast_color)->getLuminance();
        if (abs($random_lum - $contrast_lum) > $lum_differential) {
            $random_color = COLOR::fromRGB($result['rgb'])->getHex();
            return $color_pair = ['text_color' => $random_color, 'bg_color' => $contrast_color];
        } else {
            select_color_pair($base);
        }
    } else {
        $random_lum = COLOR::fromHex($result['hex'])->getLuminance();	
        $contrast_color = COLOR::fromHex($result['hex'])->invert();
        $contrast_lum = COLOR::fromHex($contrast_color)->getLuminance();
        if (abs($random_lum - $contrast_lum) > $lum_differential) {
            return $color_pair = ['text_color' => strtoupper($result['hex']), 'bg_color' => strtoupper($contrast_color)];
        } else {
            select_color_pair($base);
        }			
    }
}

Any suggestions?

Roddy

Share this post


Link to post
Share on other sites

Add a return statement before the recursive call.  You want to return the value of the recursive function.

  • Thanks 1

Share this post


Link to post
Share on other sites

Very nice. Have a great weekend!

Roddy

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...