将函数的输出设置为等于变量


Set the output of a function equal to a variable

如何将自定义 php 函数的输出设置为变量?

函数为:

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

如何将 getRandomColor1 设置为 $RandomColor 1?

我需要它是一个变量,这样我就可以在 css 中使用它,例如:

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

如果无法将其设置为变量,我如何将函数的输出放入 css 中?

好的,有许多答案指向正确的方向,但要为您详细说明:

函数需要返回所需的值。请阅读此链接,因为它是您问题的答案(感谢egasimus的链接)。

所以像这样:

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

然后

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

此外,如果您正在使用的服务器未启用正确的设置(或决定稍后禁用它),<?=可能会导致错误和安全问题。总是使用<?php echo可能更安全。

你在函数的末尾return值(例如:return $rand_col)。有关文档,请参阅此处。

如果 css 和 php 在同一个文件上,你可以这样做:

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

有关详细信息,请参阅此处。