【问题标题】:How to wrap code inside a function makes that code is not working?如何将代码包装在函数中会使该代码不起作用?
【发布时间】:2016-05-01 00:13:27
【问题描述】:

我有这段代码,它运行良好:

if(in_array($_SERVER['HTTP_HOST'], array('localhost', '127.0.0.1'))) // localhost
{
    $root = '';
}
else
{
    if(!empty($_SERVER['HTTPS'])) // https
    {
        $root = 'https'.'://'.$_SERVER['HTTPS_HOST'];
    }
    else // http
    {
        $root = 'http'.'://'.$_SERVER['HTTP_HOST'];
    }
}

我是这样回应的:

<img src="<?php echo $root.htmlspecialchars($path, ENT_QUOTES); ?>" />

我想将代码包装在函数中,例如:

function root() {
// that code
}

然后以类似的方式回显它:

<img src="<?php echo root().htmlspecialchars($path, ENT_QUOTES); ?>" />

怎么做?因为我的例子不起作用。: (

【问题讨论】:

  • 我标记的答案工作得更快,因为只有一个回报。使用您的答案,我获得了 3 次回报。我给你点赞,谢谢。
  • 我的代码中没有提到速度类型的东西。谢谢

标签: php function http server


【解决方案1】:

你的函数没有返回任何值,所以没有什么可以回显... 尝试在函数末尾添加return $root

function root()
{
    //that code
    return $root;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-07
    • 1970-01-01
    • 1970-01-01
    • 2020-04-04
    • 2017-01-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多