iwato Posted May 20, 2011 Share Posted May 20, 2011 Question: Please consider the following block of code and explain the presence of the pseudo $this variable in the statement $opts[CURLOPT_HEADERFUNCTION] = array($this, '_setHeader'); Although it is true that the callback function used for this option must contain two parameter values, these values are already taken into account when the setHeader() method is called by the curl_setopt_array() functionWhy can I not simply write $opts[CURLOPT_HEADERFUNCTION] = 'setHeader'; class Test { public $headers; public function exec($opts) { $this->headers = array(); $opts[CURLOPT_HEADERFUNCTION] = array($this, '_setHeader'); $ch = curl_init(); curl_setopt_array($ch, $opts); return curl_exec($ch); } private function _setHeader($ch, $header) { $this->headers[] = $header; return strlen($header); } } The $opts array appears with the following format $opts = array( CURLOPT_URL => 'http://www.example.com', CURLOPT_HEADER => false ); Roddy Link to comment Share on other sites More sharing options...
justsomeguy Posted May 20, 2011 Share Posted May 20, 2011 When passing a method of a class, that's how you pass it. You pass the class instance, then the method name. $this is the class instance (not a "pseudo variable"). You can't pass "$this->_setHeader" because the code which executes the callback may not be in the same scope, so $this may not point to the correct object any more since the method name gets passed as a string. So the workaround is to pass the object instance, then the method as a string. Link to comment Share on other sites More sharing options...
iwato Posted May 21, 2011 Author Share Posted May 21, 2011 When passing a method of a class, that's how you pass it. You pass the class instance, then the method name.... You can't pass "$this->_setHeader" because the code which executes the callback may not be in the same scope, so ... the workaround is to pass the object instance, then the method as a string.Still learnin'. Many thanks, JSG!Roddy Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.