1

im trying to call a function inside another function. based on some research they say using

$this->

should work. but it gave me

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);
}

to view the rest of my code :

http://pastebin.com/5ukmpYVB

error :

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

CudoX
  • 985
  • 2
  • 19
  • 31

2 Answers2

3

$this-> is needed if you are within a class, if you don't, just call the function by its name:

function test($astring) {
    $output2 = addstring($astring, 'asd', 1);
}
Nicolas Defranoux
  • 2,646
  • 1
  • 10
  • 13
0

Besides the error mentioned by Nicolas,

function test($astring) {

has no return value and does not use the parameter by reference, which means, the function is not doing anything but wasting performance.

To demonstrate how you bring the functions into 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();
Daniel W.
  • 31,164
  • 13
  • 93
  • 151