简体   繁体   English

如何在PHP中调用外部函数

[英]How to call an external function in PHP

I want to call an external function in PHP from inside of a class function, but it does not work. 我想从类函数内部调用PHP中的外部函数,但是它不起作用。

I've tried with include and require at various locations of the PHP class file, but without success. 我尝试在PHP类文件的各个位置使用include和require,但是没有成功。

The following function is located in the file Amd.php 以下功能位于文件Amd.php中

<?php

function AmdGetFirstName($sUsername){
    $oUserModel = new UserCoreModel;
    $iProfileId = $oUserModel->getId(null, $sUsername);
    $sFirstName = $oUserModel->getFirstName($iProfileId);
    unset($oUserModel);
    return $sFirstName;
}

Now I want to call this function from a class function with the following code: 现在,我想使用以下代码从类函数中调用此函数:

<?php

require_once PATH_ROOT . '/Amd.php';

class Design
{
    public function getProfileLink($sUsername)
    {
        $sFirstName = AmdGetFirstName($sUsername);

        $sHtml = '<a href="';
        $sHtml .= (new UserCore)->getProfileLink($sUsername);
        $sHtml .= '" title="' . t("%0%'s profile", $sFirstName) . '">'; 
        $sHtml .= $sFirstName . '</a>';

        echo $sHtml;
    }
}

When I debug the code the function AmdGetFirstName is not called from within the public function getProfileLink . 当我调试代码时,未从公共函数getProfileLink调用函数AmdGetFirstName If I call the same function in the index.php file with the same require_once statement it works very well. 如果我使用相同的require_once语句在index.php文件中调用相同的功能,则效果很好。 The difference what I can see is that in index.php the function is not called within another function or class function. 我所看到的区别是在index.php中,该函数未在另一个函数或类函数中调用。 I also tried to locate the require_once statement inside of the class function with the same result. 我还尝试在类函数内部找到require_once语句,结果相同。

我建议在使用dirname( FILE )时将include包含在Amd.php中,如下所示:

include (dirname(__FILE__)."/Amd.php")
<?php

class Design
{
    public function getProfileLink($sUsername)
    {
        require_once PATH_ROOT . '/Amd.php';

        $sFirstName = AmdGetFirstName($sUsername);

        $sHtml = '<a href="';
        $sHtml .= (new UserCore)->getProfileLink($sUsername);
        $sHtml .= '" title="' . t("%0%'s profile", $sFirstName) . '">'; 
        $sHtml .= $sFirstName . '</a>';

        echo $sHtml;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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