简体   繁体   中英

How do I print this returned value in php?

function printmsg($string,$type) {//type 1 = green, type 2 = red
    if($type == 1) $msg = "<p style=\"color:#00C5CD\">".$string."</p>";
    if($type == 2) $msg = "<p style=\"color:#f7110b\">".$string."</p>";
    return $msg;
}
printmsg("hello",1);

//lots of other code
print($msg);

Im trying to get my returned value to print but it never seems to work.

How about saving the return of the function in a variable and printing the variable

function printmsg($string,$type) {//type 1 = green, type 2 = red
    if($type == 1) $msg = "<p style=\"color:#00C5CD\">".$string."</p>";
    if($type == 2) $msg = "<p style=\"color:#f7110b\">".$string."</p>";
    return $msg;
}
$msg = printmsg("hello",1);

//lots of other code
print($msg);

if you are returning something you must have to catch it in some variables. Also in PHP you need to use echo to print the variables.

function printmsg($string,$type) {//type 1 = green, type 2 = red
    if($type == 1) $msg = "<p style=\"color:#00C5CD\">".$string."</p>";
    if($type == 2) $msg = "<p style=\"color:#f7110b\">".$string."</p>";
    return $msg;
}
$msg = printmsg("hello",1);

//lots of other code
echo $msg;

Just echo it

function printmsg($string,$type) {//type 1 = green, type 2 = red
    if($type == 1) $msg = "<p style=\"color:#00C5CD\">".$string."</p>";
    if($type == 2) $msg = "<p style=\"color:#f7110b\">".$string."</p>";
    return $msg;
}
echo printmsg("hello",1);

You want this:

function printmsg($string,$type) {//type 1 = green, type 2 = red
if($type == 1) $msg = "<p style=\"color:#00C5CD\">".$string."</p>";
if($type == 2) $msg = "<p style=\"color:#f7110b\">".$string."</p>";
return $msg;

} $msg=printmsg("hello",1);

//lots of other code print($msg);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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