【问题标题】:Cannot call PHP function even though it is "included"即使“包含”,也无法调用 PHP 函数
【发布时间】:2012-06-08 12:43:00
【问题描述】:

我最近开始使用 PHP...除了一件事,一切都很好。 我正在尝试从另一个 php 文件中调用一个函数……但它不起作用。 这可能真的很简单,但我没有找到任何有用的方法来解决它。

我已经使用了“required_once”,但它仍然不起作用。 有谁知道我哪里出错了?

<?php
require_once "/Applications/MAMP/htdocs/me/database_functions.php";
require_once "/Applications/MAMP/htdocs/me/encode_decode.php";

if (isset($_POST['url']) && $_POST['url'] != "http://")
{
//Get the url posted
$long_url = $_POST['url'];

//Create record in long_url table and return it's id
$long_id = create_long_url($long_url);

到目前为止一切正常.. 但是 问题是下一个函数调用..它甚至没有进入函数。

$short_url = $encode($long_id);


}...............etc...

encode_decode.php 看起来有点像这样……

<?php //encode_decode.php


function encode($number)
{
echo "<br />in encode";
//Encode numer to 6 char 
$s = strtr(rtrim(base64_encode(pack('i', $number)), '='), '+/', '-_');

echo $s;

return $s;
}

非常感谢任何帮助...

【问题讨论】:

  • $encode($long_id); 为什么要以$ 开头?

标签: php function scope


【解决方案1】:

函数调用前不需要 $

$short_url = $encode($long_id);

应该是

$short_url = encode($long_id);

【讨论】:

    【解决方案2】:

    仅当函数存储在变量中时才需要美元符号(它不是)。

    $short_url = encode($long_id);
    

    【讨论】:

      【解决方案3】:

      去掉函数前面的美元符号。 PHP 中的美元符号表示变量

      【讨论】:

        【解决方案4】:

        正如所有其他人所说:

        $short_url = encode($long_id);
        

        但你也可以清理你的 require_once 语句:

        define('DS', DIRECTORY_SEPARATOR);
        require_once(dirname(__FILE__) . DS . 'database_functions.php');
        require_once(dirname(__FILE__) . DS . 'encode_decode.php');
        

        除了define() 和对DS 的引用,您当然可以只在文件名前加上'/'。这还假设您的文件是相对的(但如果不只是将文件夹添加到文件名的前缀) - 这将确保您在从不同服务器(即测试、生产)移动站点时不会遇到任何问题。

        【讨论】:

        • 好主意,看起来干净多了!谢谢!
        • 对不起,我已经编辑了我的答案,因为我愚蠢地错过了目录分隔符,因为 dirname(FILE) 通常不会在路径的尾部添加斜杠。无论您使用的是 windows 还是 linux,使用上面的代码都可以确保安全(或者最好看看 spl_autoload 函数:php.net/manual/en/function.spl-autoload.php
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多