David Peltier
David Peltier

Reputation: 91

use of $this cakephp subfunction

I've done a search into stackoverflow but couldn't find anything.

Actually I'm working into recodding a "dirty" code done by a dev in a CakePHP 2.3 framework.

I'm not a dev myself, i'm more like a Swiss knife, i do some php but this is usually not my daily task.

:)

Let's go to the facts, i've got a controller with functions, and some functions under these functions...

Ex :

tool_controller.php

function addSomething(){

   print_r($this->loadModel("db")); //it works // returns 1

      function anotherFunction(){

         print_r($this->loadModel("db")); //returns "Using $this when not in object context"    

      }
}

I'm a bit lost, searched in CakePHP docs but couldn't find anything either.

Can someone please help ?

thanks

Upvotes: 0

Views: 109

Answers (3)

drmonkeyninja
drmonkeyninja

Reputation: 8540

This code would most probably be better written like this:-

public function addSomething(){
    print_r($this->loadModel("db"));
    $this->_anotherFunction();    
}

protected function _anotherFunction(){
    print_r($this->loadModel("db"));
}

I doubt you really need to nest functions for what you want to achieve. The above code should be simpler to read and is more obvious what context $this refers to.

Upvotes: 1

David Peltier
David Peltier

Reputation: 91

After that many of you suggest me to not to nest functions, I've decided to follow your advice and I've putted outside my main function, after I call back my function.

Public Function loopAction(){

   //Code here

}

Public Function addsomething(){

   //Code here

   $this->loopAction();

}

It works perfectly and even better than before, thanks to all.

Upvotes: 0

David Peltier
David Peltier

Reputation: 91

OK people, i've solved my problem, as I told before the main function is an action after a submit, then I had a loop inside this function to treat the datas.

As i'm working in CakePHP and using the integrated functions (in this case the function "loadModel" in the "Controller" class), i had to get this function working in the nested function.

The solution was the following :

 function addSomething(){

   my_code_here

    function anotherFunction(){

       $controller = new Controller; // Had to redeclare the class

       print_r($controller->loadModel("db")); // Works just fine

  }

}

Thanks to all for your submissions.

Kind regards folks ;)

Upvotes: 0

Related Questions