PHP'要求'echo'VS'返回'

时间:2012-12-20 08:07:23

标签: php return echo

在PHP函数中,有时我会发现某些东西可以被回显,但它无法返回。

例如,这成功回显了页面上的结果:

function get_page_id( $path ) {

global $mysqli;
if ($stmt = $mysqli->prepare("SELECT state FROM country WHERE city = ?")) {
    $stmt->bind_param("s", $city);
    $stmt->execute();
    $stmt->bind_result($state);
    $stmt->fetch();
    $stmt->close();
    echo $state;
}

}

但是,此函数不返回值:

function get_page_id( $path ) {

global $mysqli;
if ($stmt = $mysqli->prepare("SELECT state FROM country WHERE city = ?")) {
    $stmt->bind_param("s", $city);
    $stmt->execute();
    $stmt->bind_result($state);
    $stmt->fetch();
    $stmt->close();
    return $state;
}

}

是什么让一个值能够被回应而不是被返回?

$ state变量在别处调用,并作为全局变量包含在内,但未包含在示例中。有趣的是,当我改变函数以返回$ state时。'';它会像我期望的那样返回结果,但只有当我追加空字符串时才会这样做。为什么会这样?

3 个答案:

答案 0 :(得分:1)

必须回显/打印并且不返回的值的唯一示例是在某些AJAX应用程序中,其中正在运行的脚本位于不同的线程中,因此无法“返回”值。在这种情况下,必须输出值,调用XHR函数捕获该值。

您的示例未在任何位置声明$state值。除null之外,您的示例都不会回显或返回任何内容。

答案 1 :(得分:1)

However, this function does not return the value:我无法重现那种行为

e.g。

<?php
$mysqli = new mysqli('localhost', 'localonly', 'localonly', 'test');
if ($mysqli->connect_error) {
    die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
}
setup($mysqli);

$state = get_page_id('acity');
echo 'state: ', $state;

function get_page_id( $city ) {
    global $mysqli;
    if ($stmt = $mysqli->prepare("SELECT state FROM tmp_country WHERE city = ?")) {
        $stmt->bind_param("s", $city);
        $stmt->execute();
        $stmt->bind_result($state);
        $stmt->fetch();
        $stmt->close();
        return $state;
    }
}


function setup($mysqli) {
    $mysqli->query('
        CREATE TEMPORARY TABLE tmp_country (
            id int auto_increment,
            city varchar(32),
            state varchar(32),
            primary key(id),
            unique key(city)
        )
    ') or die($mysqli->error);
    $mysqli->query("INSERT INTO tmp_country (city,state) VALUES ('acity','astate'),('bcity','bstate')") or die($mysqli->error);
}

按预期在我的机器上打印state: astate

答案 2 :(得分:0)

如果你想返回并回声,你只需要这样做:

echo $state;
return $state;

返回一个值并回显它是两个不同且无关的动作。

相关问题