CodeIgniter Forums
Object inside function - Error: "Using $this when not in object context in..." - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: Object inside function - Error: "Using $this when not in object context in..." (/showthread.php?tid=8157)



Object inside function - Error: "Using $this when not in object context in..." - El Forum - 05-07-2008

[eluser]Muppit[/eluser]
I have a block of code which, using switch case, calls a function depending on a value passed via the URL.

I have loaded the eMail class within my controller, and it works fine - until I try to access the email object within my function, which is being called from the switch case.

Ex:

Code:
switch($a)
  case "add":
  funcName($email, $to);
  break;

function funcName($email, $to){
  $this->email->... // Do all eMail things here
}
Returns this error:

Fatal error: Using $this when not in object context in /file.php on line 119

But place all the code within that function outside of a function and it works perfectly.

So my question is, how do I access that object within a function? Or is it something else I'm not getting?

Appreciate any help on this,

Muppit


Object inside function - Error: "Using $this when not in object context in..." - El Forum - 05-07-2008

[eluser]gtech[/eluser]
have you tried this.. just cut and paste this example into a controller with the filename home.php in the controllers directory.

Code:
<?php
class Home extends Controller   {
  function Home(){
    parent::Controller();
  }

  function checkv($a) {
    switch($a) {
      case "add":
      $email = '[email protected]';
      $to = '[email protected]';
      $this->funcName($email, $to);
      break;
    }
  }

  function funcName($email, $to) {
    //line below not needed if autoloaded
    $this->load->library('email');

    $this->email->from($email);
    $this->email->to($to);
    print_r($this->email);
  }
}
?>

url: http://localhost/CI1.6.1/index.php/home/checkv/add


Object inside function - Error: "Using $this when not in object context in..." - El Forum - 05-07-2008

[eluser]Muppit[/eluser]
Thanks gtech, appreciate the response.

As you probably guessed my understanding is a little limited - tried your example but with no success...

I have found a solution though after consulting another mate of mine on the matter. If you're a bit of a slap happy beginner like me, read on - this might be of some assistance.

The issue was with the 'global' [ I use the term used loosely ] aspect of the $this variable which holds all the instantiations of libs & whatnot, is lost once it's attempted to be accessed within a function.

So, this:
Code:
$me_var = "rocks";

meFunc(){
  echo $me_var;
}

Is no good as the function doesn't or can't access variables set outside of itself. Same applies to classes too apparently.

So, to get around this problem I went something like this:

Code:
function funcName($ci_class){
  $ci_class->load->library('email');
  $ci_class->email->send("to","[email protected]");
}

$me_var = funcName(&$this);

The above is essentially passing the value or instantiation of the $this var into the func but re-assigning it to a new class instance once there. The ampersand, as I've just learned, creates a reference *link* to that object, rather than a whole new instance [ and therefore twice the size ] of that object, and therefore uses less memory, goes faster, etc.

Cripes I think that's right anyway ... I confuse easily but that is my understanding. If I'm wrong please set me straight.

Anyway, hope this makes sense - it's worked for me.

Cheers,

Muppit


Object inside function - Error: "Using $this when not in object context in..." - El Forum - 05-07-2008

[eluser]gtech[/eluser]
edited example to prove the $this can be referred to within a CLASS.

note that my code is within a class: (class Home extends Controller)
Code:
<?php
class Home extends Controller   {
  function Home(){
    parent::Controller();
    // If I did not use $this-> in front of the testvariable
    // it would not be 'global' within the class
    // $this-> is a reference to this class not the function.
    $this->testvariable = 'displayme';
  }

  function checkv($a) {
    switch($a) {
      case "add":
      $email = '[email protected]';
      $to = '[email protected]';
  
      // here I use $this again to access a function within the class
      $this->funcName($email, $to);
      break;
    }
  }

  function funcName($email, $to) {
    // note this function is within the CLASS and so $this is still available.

    //line below not needed if autoloaded
    $this->load->library('email');

    $this->email->from($email);
    $this->email->to($to);
    print_r($this->email);
    echo "<br><br>";
    // display me will get printed out
    echo $this->testvariable;
  }
}
?&gt;

I am very surprised my example did not work for you, as I ran it myself and it works fine.. the function funcName is called from checkv. if you create a new file called 'home.php' in the controllers directory cut and paste the WHOLE example (which i have tested and know works) and then browse to the url http://<SERVER>/<CIINSTALL>/index.php/home/checkv/add you will see the following.

Quote:CI_Email Object ( [useragent] => CodeIgniter [mailpath] => /usr/sbin/sendmail [protocol] => mail [smtp_host] => [smtp_user] => [smtp_pass] => [smtp_port] => 25 [smtp_timeout] => 5 [wordwrap] => 1 [wrapchars] => 76 [mailtype] => text [charset] => utf-8 [multipart] => mixed [alt_message] => [validate] => [priority] => 3 [newline] => [crlf] => [bcc_batch_mode] => [bcc_batch_size] => 200 [_subject] => [_body] => [_finalbody] => [_alt_boundary] => [_atc_boundary] => [_header_str] => [_smtp_connect] => [_encoding] => 8bit [_safe_mode] => [_IP] => [_smtp_auth] => [_replyto_flag] => [_debug_msg] => Array ( ) [_recipients] => [email protected] [_cc_array] => Array ( ) [_bcc_array] => Array ( ) [_headers] => Array ( [From] => [Return-Path] => ) [_attach_name] => Array ( ) [_attach_type] => Array ( ) [_attach_disp] => Array ( ) [_protocols] => Array ( [0] => mail [1] => sendmail [2] => smtp ) [_base_charsets] => Array ( [0] => us-ascii [1] => iso-2022- ) [_bit_depths] => Array ( [0] => 7bit [1] => 8bit ) [_priorities] => Array ( [0] => 1 (Highest) [1] => 2 (High) [2] => 3 (Normal) [3] => 4 (Low) [4] => 5 (Lowest) ) )

displayme

I have added an example to show how a $this reference can be used in every function WITHIN A CLASS (its only global to the class) using $this->testvariable;

For example you can declare $this->variabletest; in the class constructor (look at my example in the home function) which gets called every time a page request through the browser is made). $this->variabletest is now available within all the functions (or methods) within the Home class, as you can see from my results cut and pasted from my browser.. 'displayme' gets printed out


To me it sounds as if your function funcName is outside the controllers class and hence why $this is not available, in this instance you are correct and you have to pass the reference to $this.


I hope this makes sense.