How to Access $this variable inside nested functions in codeigniter? - php

I have a controller for Nu soap WSDL Like:
class webservice extends CI_Controller
{
function index()
{
$this->load->library('encrypt');
$this->load->model('MWSDl');
//...
function buy($apicode)
{
if(!$this->MWSDl->check_gateway($apicode)) //Error occurred php Cannot find "$this" Variable
}
//...
$this->nusoap_server->service(file_get_contents("php://input"));
}
}
How to Access $this inside buy function?
I tried by global $this But Error occurred!
Error:
Fatal error: Using $this when not in object context in \controllers\webservice.php on line 9

You are going wrong about the whole concept. PHP is not Javascript.You shouldn't nest functions, specially not when using OOP frameworks. If you run function index twice, the second time you will probably get an error that function buy is already declared since first run of index will declare function buy.
I would declare them as class member functions / methods.
class Webservice extends CI_Controller {
function __construct()
{
parent::construct();
$this->load->library('encrypt');
$this->load->model('MWSDl');
}
function index()
{
// do something like
$apicode = 'xxxxxx';
$this->buy($apicode);
//or what ever else you need to do
}
function buy($apicode)
{
if(!$this->MWSDl->check_gateway($apicode)) {
$this->nusoap_server->service(file_get_contents("php://input"));
}
}
}
No need to use globals in codeigniter.
Let me know if this helps.

I understand your question. I also had the same problem with nusoap. When registering a service you have to make a function. Thus in CI you are creating it inside a class function which makes the service function is nested inside, and cannot be taken outside.
Why don't you try this below? I use it all the time before, with helper etc. It's simple and I have tried it and it works.
Put this inside your nested function:
$ci =& get_instance();
and the rest you have to replace $this with $ci
eq. $ci->some_model->some_function(); or $ci->some_var = 'something';
And it also work if you tried to call a db.
I hope this will help you.

Related

PHP call class variable / property with stored closure

So I am making a Magento module in PHP. I want my logging to be consistent across all classes. My idea was to define a method in the helper class and call it. However being the pre-optimizer that I am, I figure making multiple calls to a class via the Mage::Helper() method to be more expensive than it needs to be, especially since most of my logging in singleton models anyways. So my now my idea is to use closures, define my method in the helper, make one call to the helper and register the method in a class variable.
class Comp_Mod_Helper_Data extends Mage_Core_Helper_Abstract {
public function getLogger() {
return function ($obj, $type= Zend_Log::DEBUG) {
Mage::log($obj, $logType, 'comp-mod.log', true);
};
}
}
Use:
class Comp_Mod__IndexController extends age_Core_Controller_Front_Action {
private $_log;
protected function _construct() {
$this->_log = Mage::Helper('mod')->getLogger();
}
}
However while it works ... it is not great to use. I'm either stuck doing:
$log = $this->_log;
$log('hello world');
// one awkward liner
($this->_log)('hello world');
While neat that it works is not readable nor standard, i.e. confusing!. The error that it get when using $this->_log('hello world'); is that the method does not exist. I assume because PHP is looking for a method call when using the syntax $this->method();
I do understand that A) I could just suck it up and use Mage::Helper everywhere, and B) that I could store the helper object in a variable and call like $this->helper->log(), and C) that static variables work, see PHP closure as static class variable
So, is there a way to get a non-static class variable to call the closure instead of looking for a non-existing method?
You could make use of the __call magic method:
class Comp_Mod__IndexController extends age_Core_Controller_Front_Action {
public function __call($method, array $args)
{
switch ($method)
{
case '_log':
return call_user_func_array(Mage::Helper('mod')->getLogger(), $args);
}
return null;
}
}
Then use it like you wanted to:
$this->_log('string to log');

Call Function From One Function To Another In A Class PHP

I would like to use a function from inside my class in another function. I have tried just calling it but it does not seem to work. Here is what I am doing:
class dog {
public function info($param) {
//Do stuff here
}
public function call($param2) {
//Call the info function here
info($param2);
//That does not seem to work though, it says info is undefined.
}
}
So basically my question is how do I call a function from another in a class. Thank You, I am VERY new to classes! :D
In PHP you always need to use $this-> to call a class method (or any attribute). In your case the code is:
public function call($param2) {
//Call the info function here
$this->info($param2);
//That does not seem to work though, it says info is undefined.
}
Please note that If you declare your method as static, then you will have to use either self:: or static::.
This is a basic PHP OOP syntax, for more information read the doc

Error: undefined property $load

I am new to codeigniter, and I have developed a code to carry out queries on the database. I load the database using$this->load->database(); and perform a query, but when I run the code, the browser gives me the following error message:
A PHP Error was encountered Severity: Notice Message: Undefined property: Tutorial::$load.
Fatal error: Call to a member function database() on a non-object
This is the code I am using:
class Tutorial extends CI_Controller {
public function tutorial() {
$this->load->database();
$query = $this->db->query('SELECT user,pass,email FROM tablex');
foreach ($query->result() as $row) {
echo $row->title;
echo $row->name;
}
I am sure the $db variables in my database configuration file are properly set and I have even tried autoloading the database for all pages in the autoload.php config file; still having the same problem. Any ideas how to go about this?
Change
$this->load->database();
to
$this->load->library('database');
database is not a direct method. It is a library in codeigniter and you have to load it as a library.
You can also autoload database library in autoload.php.
UPDATE:
You are using the same name for your class and method. In PHP4, a method which has the same name as class name was treated as constructor, but if you are using codeigniter 2+, you have to use PHP5 constructor which is
function __construct()
{
parent::__construct();
/*Additional code which you want to run automatically in every function call */
}
You cannot give a method same name as class name in Codeigniter 2+. Change the method to anything else. You can name the method index if you want it to load by default.
This should solve your problem.
CodeIgniter User Guide, Creating Libraries Section:
To access CodeIgniter's native resources within your library use the
get_instance() function. This function returns the CodeIgniter super
object.
Normally from within your controller functions you will call any of
the available CodeIgniter functions using the $this construct.
$this, however, only works directly within your controllers, your
models, or your views. If you would like to use CodeIgniter's classes
from within your own custom classes you can do so as follows:
First, assign the CodeIgniter object to a variable:
$CI =& get_instance();
Once you've assigned the object to a variable, you'll use that
variable instead of $this:
$CI =& get_instance();
$CI->load->helper('url');
$CI->load->library('session');
$CI->config->item('base_url');
etc.
Hope this helps. You could also put the $CI in a constructor.
Your code would look something like this:
class Tutorial
{
public $CI;
/**
* Constructor.
*/
public function __construct()
{
if (!isset($this->CI))
{
$this->CI =& get_instance();
}
$this->CI->load->database();
}
}

Using a custom library inside of a custom library in codeigniter?

the problem I am having is that I am trying to use a custom library inside of another custom library I made within codeigniter. They are both in the libraries folder and CodeIgniter tells me that I have to first load the instance of CI which I did...
class MyClass {
public function __construct()
{
$CI =& get_instance();
$CI->load->library("OtherClass");
}
Now inside of a function within this class I am trying to use my other library..
public function my_function()
{
$CI->otherclass->function_inside_this_class();
}
The error I am getting is
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: CI
Filename: libraries/MyClass.php
Line Number: 20
Is there something I am missing in terms of declaring the codeigniter instance itself?
Thank you!
Your CI variable scope is limited to the constructor function at the moment. You can make a class variable that has class scope and will be accessible via $this->variable in all functions within that class.
class MyClass {
private $_CI; // make a private class variable here.
public function __construct()
{
$this->_CI =& get_instance();
$this->_CI->load->library("OtherClass");
}
public function my_function()
{
$this->_CI->otherclass->function_inside_this_class();
}
I think you shouldn't use CI. Include the second_library.php and create a new class in first_library.php. Or isn't possible?

Fatal error: undefined function - why?

I'm new to object oriented programming in PHP. I included a class and called it, then, inside this class's constructor I'm calling a private function called handleConnections. For some reason, it's giving me a fatal error (undefined function). Any idea why?
The class:
class Test
{
function __construct()
{
handleConnections();
}
private function handleConnections()
{
//do stuff
}
}
It seems flawless and yet I'm getting this error. If anyone has any clue what might be wrong, please tell me. Thanks!
Just expanding on FWH's Answer.
When you create a class and assign it to a variable, from outside the class you would call any function within that class using $variable->function();. But, because you are inside the class, you don't know what the class is being assigned to, so you have to use the $this-> keyword to access any class properties. General rule of thumb, if you would access it like $obj->var, access it with $this->.
class myClass
{
function myFunc()
{
echo "Hi";
}
function myOtherFunc()
{
$this->myFunc();
}
}
$obj = new myClass;
// You access myFunc() like this outside
$obj->myFunc();
// So Access it with $this-> on the inside
$obj->myOtherFunc();
// Both will echo "Hi"
Try with:
$this->handleConnections();
If you don't prefix your calls with $this, it's trying to call a global function. $this is mandatory in PHP, even when there can be no ambiguity.

Categories