In my CakePHP 2 application I have such vendor. I need to create an instance of this vendor class inside my controller class. So I will use that instance inside my controller’s different functions.
App::import('Vendor', 'fancyVendor', array('file' => 'fancyVendor.php'));
class MyController extends AppController {
public $fancyVendor;
function beforeFilter() {
$fancyVendor = new fancyVendor();
$fancyVendor->setValue("12");
}
function showMe() {
echo $fancyVendor->getValue();
}
}
Inside my showMe function, I can’t get the value that I set inside my beforeFilter function. Is there a proper way to instantiate it?
You need to learn about scope. You have initialised a variable in the
beforeFilter()scope and then trying to use it in theshowMescope. The two are completely different.You can make a variable that is scoped to the entire class, normally called a property…
Another point to note is that you can use the
App::uses()method to load the class. According to your naming it would work. (class is lazy loaded this way)