简体   繁体   English

如何在函数内部使用switch语句来更改PHP中的变量?

[英]How do I use switch statement inside function to change variables in PHP?

I'm trying to write a PHP RGB-to-HEX converter and I'm trying to use a function to convert RGB numbers into letters if they're between 10 and 15 (and no, I can't use the "dechex()" function). 我正在尝试编写一个PHP RGB-to-HEX转换器,我试图使用一个函数将RGB数字转换为字母,如果它们在10到15之间(不,我不能使用“dechex”( )“功能”。 This is how I have it coded right now: 这就是我现在编码的方式:

function convToHex(&$hexInt)
{
    switch($hexInt){
        case 10:
            $hexInt = "A";
            break;
    }
}

//create six hexadecimal variables for "hexMain"

$hex1 = intval($r / 16);
$hex2 = $r % 16;
$hex3 = intval($g / 16);
$hex4 = $g % 16;
$hex5 = intval($b / 16);
$hex6 = $b % 16;

$rgb = "#" . $r . $g . $b;

echo convToHex($hex1);

The problem is that when I try to echo it, the value just comes up as 0. What would be the best way to convert "$hex1", "$hex2", and so-on without using "dechex()"? 问题在于,当我尝试回显它时,该值只是为0.在不使用“dechex()”的情况下转换“$ hex1”,“$ hex2”等等的最佳方法是什么?

You need to return the value ($hexInt in this case) in your function. 您需要在函数中返回值(在这种情况下为$ hexInt)。 Then, there's no need for working with a reference. 然后,没有必要使用参考。

function convToHex($hexInt) {
    // do things
    return $hexInt;
}

echo convToHex($hexInt);

Your problem is in this line: 你的问题在于这一行:

echo convToHex($hex1);

If you want to pass by reference, then you need to call the function to alter the variable, then echo it (since the function won't return the value that it alters), eg 如果你想通过引用传递,那么你需要调用函数来改变变量,然后回显它(因为函数不会返回它改变的值),例如

convToHex($hex1);
echo $hex1;

...also, any reason not to use something like: ......还有,任何不使用以下内容的理由:

function rgb2hex($r, $g, $b) {
  return sprintf("#%02X%02X%02X", $r, $g, $b);
}

or, if you want something closer to your original logic: 或者,如果你想要更接近原始逻辑的东西:

function rgb2hex($r, $g, $b) {
  // takes ints $r, $g, $b in the range 0-255 and returns a hex color string
  $hex_digits = "0123456789ABCDEF";
  $hex_string = "";

  $hex_string .= substr($hex_digits, $r / 16, 1);
  $hex_string .= substr($hex_digits, $r % 16, 1);
  $hex_string .= substr($hex_digits, $g / 16, 1);
  $hex_string .= substr($hex_digits, $g % 16, 1);
  $hex_string .= substr($hex_digits, $b / 16, 1);
  $hex_string .= substr($hex_digits, $b % 16, 1);

  return "#" . $hex_string;
}

to use either of these would involve something like: 使用其中任何一个都会涉及到:

$r = 12;
$g = 234;
$b = 45;

$hex_string = rgb2hex($r, $g, $b);
echo $hex_string . "\n";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM