php调用函数中的另一个函数

时间:2014-04-23 15:05:44

标签: php function

我试图在另一个函数内调用一个函数。根据一些研究,他们说使用

  

$这 - >

应该有效。但它给了我

  

致命错误:不在对象上下文中时使用$ this

function addstring($input, $addition_string , $position) {
    $output = substr_replace($input, $addition_string, $position, 0);
    return $output;
}


function test($astring) {
    $output2 = $this->addstring($astring, 'asd', 1);
}

查看我的其余代码:

  

http://pastebin.com/5ukmpYVB

错误:

  

致命错误:在第48行的BLA.php中不在对象上下文中时使用$ this

2 个答案:

答案 0 :(得分:3)

$这 - >如果你在课堂上是必需的,如果你不在,只需按名称调用该功能:

function test($astring) {
    $output2 = addstring($astring, 'asd', 1);
}

答案 1 :(得分:0)

除了Nicolas提到的错误,

function test($astring) {

没有返回值,也没有通过引用使用参数,这意味着该函数除了浪费性能外没有做任何事情。

演示如何将功能纳入class context

class StringHelper
{
    private $output;

    protected function addstring($input, $addition_string , $position) {
        $output = substr_replace($input, $addition_string, $position, 0);
        return $output;
    }

    public function test($astring) {
        $this->output = $this->addstring($astring, 'asd', 1);
        return $this;
    }

    public function getOutput() {
        return $this->output;
    }
}


$stringObj = new StringHelper;
echo $stringObj->test('my string')->getOutput();