将函数的输出设置为等于变量 [英] Set the output of a function equal to a variable

查看:83
本文介绍了将函数的输出设置为等于变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

函数是:

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

我如何将getRandomColor1设置为等于$ RandomColor1?

How would i set getRandomColor1 equal to $RandomColor1?

我需要将其作为变量,以便可以在CSS中使用它,例如:

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

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

如果无法将其设置为变量,我还能怎么放函数输出到css中?

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

推荐答案

好,有很多答案都指向正确的方向,但是为您说明问题:

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

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

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).

所以类似这样:

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

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.

这篇关于将函数的输出设置为等于变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆