2014-04-23 39 views
1

即時嘗試調用另一個函數內的函數。基於他們說的一些研究使用php調用函數中的另一個函數

$this->

應該工作。但它給了我

Fatal error: Using $this when not in object context

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

錯誤:

Fatal error: Using $this when not in object context in BLA.php on line 48

+3

*「來查看我的代碼的其餘部分」 * ---你有足夠的代表處點張貼。 –

+4

只要刪除'$ this->' –

+2

或更好的是,添加一個類。 – Brad

回答

3

$這個 - 如果你是一個類中>需要,如果你不知道,只需通過其名稱調用函數:

function test($astring) { 
    $output2 = addstring($astring, 'asd', 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();