Reputation: 34006
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?
Upvotes: 0
Views: 845
Reputation: 7585
You need to learn about scope. You have initialised a variable in the beforeFilter()
scope and then trying to use it in the showMe
scope. The two are completely different.
You can make a variable that is scoped to the entire class, normally called a property...
function beforeFilter() {
$this->fancyVendor = new fancyVendor();
$this->fancyVendor->setValue("12");
}
function showMe() {
echo $this->fancyVendor->getValue();
}
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)
App::uses('fancyVendor', 'Vendor');
Upvotes: 2