Set the output of a function equal to a variable

2020-05-08 08:14发布

问题:

How would i set the output of a custom php function to a variable?

The function is:

function getRandomColor1() {
global $cols;
$num_cols = count($cols);
$rand = array_rand($cols);
$rand_col = $cols[$rand];
echo $rand_col;
unset($cols[$rand]);
}

How would i set getRandomColor1 equal to $RandomColor1?

I need it to be a variable so I can use it in css like:

#boxone1 {  
height: 150px;
width: 150px;
background: <?=$RandomColor1?>; 
float: left;
} 

If its not possible to set it as a variable, how else could i put the output of the function into css?

回答1:

OK, there are a number of answers that are pointing in the right direction, but to spell things out for you:

Your function needs to return the value that you want. Please read this link, since it is the answer to your question (thanks to egasimus for the link).

So something like this:

function getRandomColor1() {
    global $cols;
    $num_cols = count($cols);
    $rand = array_rand($cols);
    $rand_col = $cols[$rand];
    unset($cols[$rand]);
    return $rand_col;
}

And then

#boxone1 {  
    height: 150px;
    width: 150px;
    background: <?php echo getRandomColor1(); ?>; 
    float: left;
}

Also, <?= can lead to bugs and security issues if the server you're working with doesn't have the proper setting enabled (or decides to disable it later). It's probably safer to just always use <?php echo.



回答2:

You return the value at the end of your function (e.g.: return $rand_col). See this for the docs.



回答3:

If the css and the php are on the same file, you could do:

background: <?=getRandomColor1();?>; 


回答4:

#boxone1 {  
    height: 150px;
    width: 150px;
    background: <?php echo $yourVariable; ?>; 
    float: left;
} 

See this for more info.



标签: php css function